r - 在保存()时重命名 R 对象 [英] r - Rename R object while save()-ing it

查看:41
本文介绍了r - 在保存()时重命名 R 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来 save() 在 R 中以不同名称即时"创建一个变量(请耐心等待!我很确定这不是重复的...)这是我想要实现的示例:

I'm looking for a way to save() a variable under a different name "on the fly" in R (bear with me! I'm pretty sure that's not a duplicate...). Here is an example of what I'd like to achieve:

AAA = 1
BBB = 2
XXX = 3
YYY = 4
save(AAA=XXX, BBB=YYY, file="tmp.Rdat")  
# does NOT save a variable AAA to file with value 3 in it, which is the aim...

基本上我希望 save() 函数获取 XXX 的值并将其保存到名为 AAA 的变量下的文件中.请注意,这不是关于重命名变量的问题:我当然可以在保存之前重命名变量 XXX,例如AAA = XXX 然后 save(AAA, ..., file=...) 但这当然会与 AAA 的值混淆code> 在其余代码中.

Basically I would like the save() function to take the value of XXX and save it to file under a variable named AAA. Note that this is not a question about renaming a variable: I could of course rename the variable XXX prior to saving, e.g. AAA = XXX and then save(AAA, ..., file=...) but this would of course mess up with the value of AAA in the rest of the code.

显而易见的方法是创建临时变量,然后恢复值:

The obvious way is to create temporary variables and then restore the values:

AAA = 1
BBB = 2
XXX = 3
YYY = 4
AAAtmp = AAA; BBBtmp = BBB      # record values of AAA, BBB
AAA = XXX; BBB = YYY
save(AAA, BBB, file="tmp.Rdat")
AAA = AAAtmp; BBB = BBBtmp      # restore values of AAA, BBB

...但每个人都会同意这是相当混乱的(尤其是有更多的变量).

... but everyone will agree that this is quite messy (especially with many more variables).

这一直困扰着我一段时间,我的感觉是函数 save() 不能做我想做的事.所以我想我将不得不更新我的代码并继续使用不同的保存功能(例如 saveRDS()).

This has been bugging me for a while, and my feeling is that the function save() can't do what I want. So I guess I will have to update my code and go down the path of using a different saving function (e.g. saveRDS()).

感谢您的帮助!

推荐答案

事实证明,这比我预期的要复杂一些.我很想看看其他人提出了什么,以及对我的解决方案有什么异议.

This proved to be a little trickier that I expected. I'll be interested to see what others come up with, and also what any objections to my solution may be.

saveit <- function(..., file) {
  x <- list(...)
  save(list=names(x), file=file, envir=list2env(x))
}

foo <- 1
saveit(bar=foo, file="hi.Rdata")

这篇关于r - 在保存()时重命名 R 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆