Symbols
When you define a variable in R, you are actually assigning a symbol to a value in an environment. For example, when you enter the statement:
> x <- 1
on the R console, it assigns the symbol x
to a vector object of length 1 with the
constant (double) value 1 in the global environment. When the R
interpreter evaluates an expression, it evaluates all symbols. If you
compose an object from a set of symbols, R will resolve the symbols at
the time that the object is constructed:
> x <- 1 > y <- 2 > z <- 3 > v <- c(x, y, z) > v [1] 1 2 3 > # v has already been defined, so changing x does not change v > x <- 10 > v [1] 1 2 3
It is possible to delay evaluation of an expression so that symbols are not evaluated immediately:
> x <- 1 > y <- 2 > z <- 3 > v <- quote(c(x,y,z)) > eval(v) [1] 1 2 3 > x <- 5 > eval(v) [1] 5 2 3
It is also possible to create a promise object in R to delay evaluation of a variable until it is (first) needed. You
can create a promise object through the delayedAssign
function:
> x <- 1 > y <- 2 > z <- 3 > delayedAssign("v", c(x,y,z)) > x <- 5 > v [1] 5 2 3
Promise objects are used within packages to make objects available to users without loading them into memory. Unfortunately, it is not possible to determine if an object is a promise object, nor is it possible to figure out the environment in which it was created.
Get R in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.