R Objects DataTypes 2 - gizotso/R GitHub Wiki

Expression

x = 3; y = 2.5; z = 1
## expression(x/(y + exp(z)))
exp1 = expression(x / (y + exp(z)))
eval(exp1) ## [1] 0.5749019
exp1 <- expression(x^2)
<=> parse(text = 'x^2')

eval(x) # 4 (with x = 2)
# D() derivees partielles
D(exp1, "y") ## [1] 0
D(exp1, "x") ## 2 * x (class:call)

d_exp1_x = D(exp1, "x") #2 * x
eval(d_exp1_x) # 4

deparse(exp1) # deparse turns unevaluated expressions into character strings.
[1] "expression(x^2)"
length(ex3 <- expression(u, v, 1+ 0:9)) # 3
ex3[3] ## expression(1 + 0:9)
mode(ex3 [3])   # expression
mode(ex3[3](/gizotso/R/wiki/3))  # call  ex3[3](/gizotso/R/wiki/3) > 1 + 0:9
rm(ex3)

substitute(expr, env): returns the parse tree for the (unevaluated) expression expr, substituting any variables bound in env.

substitute(expression(a + b), list(a = 1))
s.e = substitute(expression(a + b), list(a = 1))    
## expression(1 + b)
# class:"call"  mode:"call"  typeof:"language"

s.s = substitute( a + b, list(a = 1))   
## 1 + b                
# class:"call"  mode:"call"  typeof:"language"

e.s.e = eval(s.e)
## expression(1 + b)
c(mode(e.s.e), typeof(e.s.e))  
## "expression", "expression"

parse, deparse

  • parse returns the parsed but unevaluated expressions in a list.
  • deparse turns unevaluated expressions into character strings.

parse

cat("x <- c(1, 4)\n  x ^ 3 -10 ; outer(1:7, 5:9)\n", file = "xyz.Rdmped")

# parse 3 statements from the file "xyz.Rdmped"
> parse(file = "xyz.Rdmped", n = 3)
## expression(x <- c(1, 4), x ^ 3 -10, outer(1:7, 5:9))

unlink("xyz.Rdmped")

deparse

deparse(args(lm), width = 500)
[1] "function (formula, data, subset, weights, na.action, method = \"qr\", model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...) "
[2] "NULL"  
foo = function(x) {
  cat('input arg is',deparse(substitute(x)), '=' , x)
}
a = 5
foo(a)
# input arg is a = 5
deparse(substitute(x)) ## [1] "x"
myplot <- function(x, y) {
    plot(x, y, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)))
}
a = 1:10; b=rnorm(10)
myplot(a,b) ## labels on the lpot will be "a" and "b"
data <- data.frame(resp = rnorm(10), expl = rep(c("A", "B"), 5))
chaine <- "lm(resp ~ expl, data = data)"

# parse retourne l'expression, non évaluée
express <- parse(text = chaine)
express
#expression(lm(resp ~ expl, data = data))

# eval évalue une expression (ici retourne le linear model de resp ~ exp1)
eval(express)

# Call:
#   lm(formula = resp ~ expl, data = Data)
#
# Coefficients:
#   (Intercept)        explB  
# -0.3551       0.7100  

 # deparse: contraire de parse...
deparse(express)
"expression(lm(resp ~ expl, data = Data))"
# substitute: substitue les éléments d'une expression par leur valeur
expr <- substitute(paste("lm(", v1, "~", v2, ", data =", v3, ")")
                   ,list(v1 = "resp", v2 = "expl", v3 = "Data"))
expr ##class: call
# paste("lm(", "resp", "~", "expl", ", data =", "data", ")")  


chaine <- eval(expr)
chaine
# [1] "lm( resp ~ expl , data = data )"


expr_chaine <- parse(text = chaine)
expr_chaine
#expression(lm(resp ~ expl, data = Data))

eval(expr_chaine)

# Call:
#   lm(formula = resp ~ expl, data = Data)
#
# Coefficients:
#   (Intercept)        explB  
# -0.3551       0.7100  

Formulae

class(y~x)

  • class : formula
  • mode : call
  • typeof : language
  • is.call()
class(y~x)
[1] "formula"

f = y ~ x1 + x2
class(f)  #[1] "formula"
mode(f)   #[1] "call"
typeof(f) #[1] "language"

Function

  • class: expression
  • mode: expression
  • typeof: closure
CV <- function(x) {
   sd(x)/mean(x)
}

CV(c(1,2,3))

Calls

  • class : call
  • mode : call
  • typeof : language
  • is.call()

http://adv-r.had.co.nz/Expressions.html#calls

cl  = call("round", 10.5)
eval(cl)    ## 10

enquote(cl) ## quote(round(10.5))
x = 10.5
cl = call("round", x)        ## round(10.5)
cl = call("round", quote(x)) ## round(x)
enquote(cl)                  ## quote(round(x))
f <- round #class:"function"
(g <- as.call(list(f, quote(A))))  ##.Primitive("round")(10.5)
eval(g)
x <- quote(read.csv("important.csv", row.names = FALSE))
x #read.csv("important.csv", row.names = FALSE)
  # class:call, mode:call, typeof:language


x[1](/gizotso/R/wiki/1) #read.csv
x[2](/gizotso/R/wiki/2) #[1] "important.csv"
x$row.names #[1] FALSE
x[3](/gizotso/R/wiki/3) #[1] FALSE

eval(x)

To create a new call from its components, you can use call() or as.call(). The first argument to call() is a string which gives a function name. The other arguments are expressions that represent the arguments of the call.

x = call(":", 1, 10)
# class:call, mode:call, typeof:language
#1:10
class(x) #[1] "call"
eval(x)
#[1]  1  2  3  4  5  6  7  8  9 10
call("mean", quote(1:10), na.rm = TRUE)
z <- quote(y <- x * 10)
z #(mode:call, class:"<-", typeof:language)
#y <- x * 10
# quote() returns an expression: an object that represents an action that can be performed by R.
ast(y <- x * 10)

x=5
deparse(eval(z)) #[1] "50"

Environment

Environments consist of a frame, or collection of named objects, and a pointer to an enclosing environment.

> environment()
<environment: R_GlobalEnv>
e1 <- new.env() ##<environment: 0x05e9ddcc>
e1$a <- 10
e1$b <- 20
as.list(e1)
library(devtools)
parenvs(all = TRUE)

as.environment("package:stats")

globalenv()  ## <environment: R_GlobalEnv>  <=> .GlobalEnv
baseenv()    ## <environment: base>
.BaseNamespaceEnv
emptyenv()   ##<environment: R_EmptyEnv>
environment() ##<environment: R_GlobalEnv>  (current active env)

parent.env(globalenv()) #lookup parent env
#<environment: 0x05ea48a4>
#  attr(,"name")

parent.env(emptyenv())
## Error in parent.env(emptyenv()) : the empty environment has no parent
#[1] "tools:rstudio

# view the objects saved in an environment with ls or ls.str
ls(globalenv())

#R’s $ syntax to access an object in a specific environment. For example, you can access deck from the global environment:
head(globalenv()$deck, 3)
# assign function to save an object into a particular environment
assign("new", "Hello Global", envir = globalenv())
globalenv()$new ## "Hello Global"


# runtime env
show_env <- function(){
  list(ran.in = environment(),
       parent = parent.env(environment()),
       objects = ls.str(environment()))
}

foo <- "take me to your runtime"
show_env <- function(x = foo){
  list(ran.in = environment(),
       parent = parent.env(environment()),
       objects = ls.str(environment()))
}
show_env(421)

See also good article : Advanced R / Environments: http://adv-r.had.co.nz/Environments.html

e = new.env() ##<environment: 0x05ead274>
e$b = 1
ls(e)