如何将工作区图像保存到R函数中的指定位置

时间:2014-04-01 18:15:54

标签: r scoping

我想将全局工作区图像保存在R函数中,但遇到了一个范围问题。这是一个如何运作的例子:

rm(list=ls())

SaveData <- function(fname) {
  # I have to use save instead of save.image due to separate constraints
  save(list=ls(), file=fname, envir=.GlobalEnv)
}

# Test
x <- 1
SaveData("~/SaveDataTest.RData")

rm(list=ls())
load("~/SaveDataTest.RData")
ls() # Would look for this to include x

SaveData("~/SaveDataTest.RData")行会引发以下错误:

Error in save(list = ls(), file = fname, envir = .GlobalEnv) :  
object ‘fname’ not found 

这表明将envir=.GlobalEnv传递给save函数会将整个函数的环境切换为.GlobalEnv。我怎么能绕过这个?

1 个答案:

答案 0 :(得分:1)

list=ls()替换envir=.GlobalEnv + list=ls(.GlobalEnv)有效:

SaveData <- function(fname) {
  save(list=ls(.GlobalEnv), file=fname)
}