问题描述
可能的重复:
如何使用特定变量名保存() >
我想知道在 R 中保存对象的简单方法是使用变量 objectName
和要保存的对象的名称.我希望这样可以轻松保存对象,并在文件名中使用它们的名称.
I'm wondering what an easy way is to save an object in R, using a variable objectName
with the name of the object to be saved. I want this to easy save objects, with their name in the file name.
我尝试使用 get
,但我没能用它的原始对象名称保存对象.
I tried to use get
, but I didn't manage to save the object with it's original object name.
示例:
如果我有一个名为temp"的对象,我想将其保存在目录dataDir"中.我将对象的名称放在变量objectName"中.
If I have the object called "temp", which I want to save in the directory "dataDir". I put the name of the object in the variable "objectName".
尝试 1:
objectName<-"temp"
save(get(objectName), file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))
这不起作用,因为 R 试图保存一个名为 get(objectName)
的对象,而不是这个调用的结果.所以我尝试了以下方法:
This didn't work, because R tries to save an object called get(objectName)
, instead of the result of this call. So I tried the following:
尝试 2:
objectName<-"temp"
object<-get(objectName)
save(object, file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))
这显然不起作用,因为 R 以名称object"保存对象,而不是以名称temp"保存对象.加载后我有一个对象"的副本,而不是临时".(是的,内容相同……但这不是我想要的:)).所以我认为它应该是带有指针的东西.所以尝试了以下方法:
This obviously didn't work, because R saves the object with name "object", and not with name "temp". After loading I have a copy of "object", instead of "temp". (Yes, with the same contents...but that is not what I want :) ). So I thought it should be something with pointers. So tried the following:
尝试 3:
objectName<-"temp"
object<<-get(objectName)
save(object, file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))
与尝试 2 的结果相同.但我不确定我在做什么我认为我在做什么.
Same result as attempt 2. But I'm not sure I'm doing what I think I'm doing.
对此有什么解决方案?
推荐答案
尝试 save(list=objectName, file=paste(objectName, '.Rdata', sep='') )
.
关键是 save
的 list
参数需要一个字符串列表,它是要保存的对象的名称(而不是通过 ).
The key is that the list
argument to save
takes a list of character strings that is the names of the objects to save (rather than the actual objects passed through ...
).
这篇关于使用带有对象名称的变量保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!