我想将全局工作区图像保存在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。我怎么能绕过这个?
答案 0 :(得分:1)
用list=ls()
替换envir=.GlobalEnv
+ list=ls(.GlobalEnv)
有效:
SaveData <- function(fname) {
save(list=ls(.GlobalEnv), file=fname)
}