In the following test, the variable x is supposed to be modified within the function test.save.x. It works as expected util using the save command. # initialize x.file x <- 1 save(x, file="x.file") rm(x) # Remove x from R_GlobalEnv exists("x") # FALSE # define test test.save.x <- function(){ save.x <- function(){ save(x, file="x.file") } change.x <- function(){ load("x.file", parent.frame(n = 2)) # load x to upper level frame x <<- x + 1 save.x() # If comment this line. x variable will not appear in R_GlobalEnv } change.x() } test.save.x() exists("x") # TRUE. Why? [[alternative HTML version deleted]]
Duncan Murdoch
2012-Sep-29 14:16 UTC
[R] About the scope of a variable and the save() method
On 12-09-28 11:51 PM, Qiang Wang wrote:> In the following test, the variable x is supposed to be modified within the > function test.save.x. It works as expected util using the save command. > > # initialize x.file > x <- 1 > save(x, file="x.file") > rm(x) # Remove x from R_GlobalEnv > exists("x") # FALSE > > # define test > test.save.x <- function(){ > save.x <- function(){ > save(x, file="x.file") > } > change.x <- function(){ > load("x.file", parent.frame(n = 2)) # load x to upper level frameThe upper level frame is globalenv(), so this is the line that creates x.> x <<- x + 1 > save.x() # If comment this line. x variable will not appear in R_GlobalEnvThis comment is false. save.x() doesn't create any new variable, it just creates a file.> } > change.x() > } > > test.save.x() > exists("x") # TRUE. Why?Because you created it by your call to load(). Duncan Murdoch