Examples for 'base::delayedAssign'


Delay Evaluation and Promises

Aliases: delayedAssign promise promises

Keywords: programming data

### ** Examples

msg <- "old"
delayedAssign("x", msg)
substitute(x) # shows only 'x', as it is in the global env.
msg
msg <- "new!"
x # new!
[1] "new!"
delayedAssign("x", {
    for(i in 1:3)
        cat("yippee!\n")
    10
})

x^2 #- yippee
yippee!
yippee!
yippee!
[1] 100
x^2 #- simple number
[1] 100
ne <- new.env()
delayedAssign("x", pi + 2, assign.env = ne)
## See the promise {without "forcing" (i.e. evaluating) it}:
substitute(x, ne) #  'pi + 2'
pi + 2
## Don't show: 
stopifnot(identical(substitute(x,ne), quote(pi + 2)))
## End(Don't show)

### Promises in an environment [for advanced users]:  ---------------------

e <- (function(x, y = 1, z) environment())(cos, "y", {cat(" HO!\n"); pi+2})
## How can we look at all promises in an env (w/o forcing them)?
gete <- function(e_) {
   ne <- names(e_)
   names(ne) <- ne
   lapply(lapply(ne, as.name),
          function(n) eval(substitute(substitute(X, e_), list(X=n))))
}
(exps <- gete(e))
$x
cos

$y
[1] "y"

$z
{
    cat(" HO!\n")
    pi + 2
}
sapply(exps, typeof)
          x           y           z 
   "symbol" "character"  "language" 
(le <- as.list(e)) # evaluates ("force"s) the promises
 HO!
$x
function (x)  .Primitive("cos")

$y
[1] "y"

$z
[1] 5.141593
stopifnot(identical(le, lapply(exps, eval))) # and another "Ho!"
 HO!

[Package base version 4.2.3 Index]