Search code examples
rfunctionsavestate

R - Saving image within function is not loading


This below code can be loaded with the SoStuck object existing:

Im <- c(1,2,3,4)
Stuck <- c(6,7,8,9)
SoStuck <- data.frame(Im, Stuck)
save.image("image.RData")

I then quit out of this session and start another. I do this:

load("image.RData")

It works:

SoStuck
   Im  Stuck
1  1     6
2  2     7
3  3     8
4  4     9

However, if I do this:

myfunction <- function()
{
  Im <- c(1,2,3,4)
  Stuck <- c(6,7,8,9)
  SoStuck <- data.frame(Im, Stuck)
  save.image("image.RData")
}
myfunction()

Restarting R, loading and then calling does not find the object:

load("image.RData")
SoStuck
Error: object 'SoStuck' not found

I have also tried return(save.image("image.RData")) in that loop and get the same error.

Anyone know what I need to change to load the file if it was saved inside a function? Thanks.


Solution

  • According to the documentation of save.image, "save.image() is just a short-cut for ‘save my current workspace’, i.e., save(list = ls(all.names = TRUE), file = ".RData", envir = .GlobalEnv)."

    So to get your function to work, you can modify your code like this:

    myfunction <- function()
    {
      Im <- c(1,2,3,4)
      Stuck <- c(6,7,8,9)
      SoStuck <- data.frame(Im, Stuck)
      save(list = ls(all.names = TRUE), file = "image.RData", envir = 
      environment())
    }
    myfunction()
    
    load("image.RData")