如何将对象加载到从R数据文件中指定的变量名称中? [英] How can I load an object into a variable name that I specify from an R data file?

查看:292
本文介绍了如何将对象加载到从R数据文件中指定的变量名称中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用save将变量保存在R数据文件中时,该变量将以其在保存该变量的会话中使用的任何名称进行保存.稍后当我从另一个会话中加载它时,它以相同的名称加载,加载脚本可能无法知道该名称.该名称可能会覆盖加载会话中同名的现有变量.有没有一种方法可以安全地将数据文件中的对象加载到指定的变量名称中,而不会破坏现有变量?

When you save a variable in an R data file using save, it is saved under whatever name it had in the session that saved it. When I later go to load it from another session, it is loaded with the same name, which the loading script cannot possibly know. This name could overwrite an existing variable of the same name in the loading session. Is there a way to safely load an object from a data file into a specified variable name without risk of clobbering existing variables?

x = 5
save(x, file="x.Rda")

加载会话:

x = 7
load("x.Rda")
print(x) # This will print 5. Oops.

我希望它如何工作:

x = 7
y = load_object_from_file("x.Rda")
print(x) # should print 7
print(y) # should print 5

推荐答案

如果只保存一个对象,请不要使用.Rdata文件,请使用.RDS文件:

If you're just saving a single object, don't use an .Rdata file, use an .RDS file:

x <- 5
saveRDS(x, "x.rds")
y <- readRDS("x.rds")
all.equal(x, y)

这篇关于如何将对象加载到从R数据文件中指定的变量名称中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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