4

Is there a way to force the evaluation of multiple variables using a character vector?

for example:

x = 1
y = 2

instead of doing this:

force( x )
force( y )

do something like this:

force( ls() )
Suraj
  • 35,905
  • 47
  • 139
  • 250
  • Can you elaborate on how you are hoping to use such functionality? – Ricardo Saporta Dec 09 '12 at 02:09
  • Carl - Not much =) I took the lazy-man approach and posted here. – Suraj Dec 09 '12 at 22:39
  • Ricardo - Its a bit complicated. I have a situation where some code is running in parallel (package 'parallel' and 'foreach') but instead of passing evaluated values, the parallel code is passing a promise. This would be ok if the promise can be resolved, but the new parallel processes do not have access to the same environments that the promise does. So I need to force evaluation before running my task in parallel so that the promise is resolved and the values are passed, not the promises. Like I said...complicated! =) – Suraj Dec 09 '12 at 22:41

1 Answers1

5

Replacing force() with eval(as.symbol()) will do the trick:

## Modified from an example in ?force (h.t. @flodel)
g <- function(x,y) {
    lapply(ls(), function(X) eval(as.symbol(X))) 
    function() x+y 
}
lg <- vector("list", 4)
for (i in 1:2) for (j in 1:2) lg[[i+j-1]] <- g(i,j)
lg[[1]]()
# [1] 2

This works because, as noted in ?force:

[force] is semantic sugar: just evaluating the symbol will do the same thing

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455