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 13:49

In case anyone is looking to do this with a plain source file, rather than a saved Rdata/RDS/Rda file, the solution is very similar to the one provided by @Hong Ooi

load_obj <- function(fileName) {

  local_env = new.env()
  source(file = fileName, local = local_env)

  return(local_env[[names(local_env)[1]]])

}

my_loaded_obj = load_obj(fileName = "TestSourceFile.R")

my_loaded_obj(7)

Prints:

[1] "Value of arg is 7"

And in the separate source file TestSourceFile.R

myTestFunction = function(arg) {
  print(paste0("Value of arg is ", arg))
}

Again, this solution only works if there is exactly one file, if there are more, then it will just return one of them (probably the first, but that is not guaranteed).

查看更多
Deceive 欺骗
3楼-- · 2020-01-25 13:52

You could also try something like:

# Load the data, and store the name of the loaded object in x
x = load('data.Rsave')
# Get the object by its name
y = get(x)
# Remove the old object since you've stored it in y 
rm(x)
查看更多
太酷不给撩
4楼-- · 2020-01-25 13:53

I'm extending the answer from @ricardo to allow selection of specific variable if the .Rdata file contains multiple variables (as my credits are low to edit an answer). It adds some lines to read user input after listing the variables contained in the .Rdata file.

loadRData <- function(fileName) {
  #loads an RData file, and returns it
  load(fileName)
  print(ls())
  n <- readline(prompt="Which variable to load? \n")
  get(ls()[as.integer(n)])
}

select_var <- loadRData('Multiple_variables.Rdata')

查看更多
不美不萌又怎样
5楼-- · 2020-01-25 13:57

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)
查看更多
迷人小祖宗
6楼-- · 2020-01-25 13:58

I use the following:

loadRData <- function(fileName){
#loads an RData file, and returns it
    load(fileName)
    get(ls()[ls() != "fileName"])
}
d <- loadRData("~/blah/ricardo.RData")
查看更多
在下西门庆
7楼-- · 2020-01-25 14:04

Rdata file with one object

assign('newname', get(load('~/oldname.Rdata')))
查看更多
登录 后发表回答