gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:14:50 25 4
gpt4 key购买 nike

这是非常基本的(我怀疑其他地方也有人问过这个问题,尽管不完全是 here)。

我有大量的 .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"

我如何使用 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"

最佳答案

如果您确定所有文件只包含一个对象,您可以在包装函数中利用 loadenvir 参数,如下所示:

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

用法如下:

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

关于R,使用 load() 从 .rda 对象分配内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34925668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com