[R] Environment question
ALBERTO VIEIRA FERREIRA MONTEIRO
albmont at centroin.com.br
Fri Oct 23 17:08:24 CEST 2015
>From the code below:
y <- 1
f1 <- function() {
cat("y =", y, "\n")
}
f2 <- function() {
y <- 2
f1()
}
f3 <- function() {
y <- 3
f <- f1
f()
}
f4 <- function() {
y <- 4
f <- function() { cat("y =", y, "\n") }
f()
}
f1()
f2()
f3()
f4()
Clearly, f1(), f2() and f4() will display "y = 1", "y = 1" and "y = 4",
but, not as much clearly but predictably, f3() also displays "y = 1".
Is there any way to rewrite the code of f3 in such a way that it
displays "y = 3"?
An obvious but cumbersome way would be something like:
f3 <- function() {
y <- 3
# write the code of f1 to a temporary file
dump("f1", "temp.R")
# read the code of f1
str <- readLines("temp.R")
# replace the code that defines function f1 for a code that defines function f
str <- gsub("f1 <-", "f <-", str)
# write the new code to the temporary file
writeLines(str, "temp.R")
# read the source but use local to get things from f3's environment
# (with the default local = FALSE, "y" would get the value from globalenv())
source("temp.R", local = TRUE)
# ...?
f()
# PROFIT!
}
Is there a more elegant way to do this?
Alberto Monteiro
More information about the R-help
mailing list