R,使用 load() 从 .rda 对象分配内容

use*_*672 3 types load r rda

这是非常基本的(我怀疑其他地方已经问过这个问题,尽管这里不完全是这样)。

我有大量 .rda 文件,每个文件都有一个数据帧。我想对每个数据帧进行计算,因此需要加载它们(load())。如果它们是 .RDS 对象,我会这样:

#My data
x <- data.frame(a=1:3)
y <- data.frame(a=3:6)

#Save as RDS 
saveRDS(x, file = "x.rds")
saveRDS(y, file = "y.rds")

files <- c("x.rds", "y.rds")
data <- lapply(files, readRDS)

#Do something with the data in the list "data"
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用做类似的事情,load因为你不能将数据(只能是名称)分配给变量:

x <- data.frame(a=1:3)

> x
  a
1 1
2 2
3 3

save(x, file= "x.rda")
x <- load("x.rda")

> x
[1] "x"
Run Code Online (Sandbox Code Playgroud)

nru*_*ell 5

如果您确定所有文件仅包含一个对象,则可以利用包装函数中envir的参数,如下所示:load

load_object <- function(file) {
  tmp <- new.env()
  load(file = file, envir = tmp)
  tmp[[ls(tmp)[1]]]
}
Run Code Online (Sandbox Code Playgroud)

用法如下:

not_x <- data.frame(xx = 1:5)
save(not_x, file = "~/tmp/x.Rdata") 

(x <- load_object("~/tmp/x.Rdata"))
#  xx
#1  1
#2  2
#3  3
#4  4
#5  5

all.equal(not_x, x)
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)