How can I load an object into a variable name that

2020-01-25 13:20发布

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?

Example:

Saving session:

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

Loading session:

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

How I want it to work:

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

7条回答
爷的心禁止访问
2楼-- · 2020-01-25 14:06

You can create a new environment, load the .rda file into that environment, and retrieve the object from there. However, this does impose some restrictions: either you know what the original name for your object is, or there is only one object saved in the file.

This function returns an object loaded from a supplied .rda file. If there is more than one object in the file, an arbitrary one is returned.

load_obj <- function(f)
{
    env <- new.env()
    nm <- load(f, env)[1]
    env[[nm]]
}
查看更多
登录 后发表回答