在不同的 R 工作区中组合同一列表的不同元素

Combine different elements of the same list in different R workspaces

例如:三个 R 工作区 A.RDataB.RDataC.RData

我想在新工作区中得到的是一个对象 list.new.example 打印为:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]  
[1] 3  

[[4]]  
[1] 4

我试过了

file.full <- list.files(directory, full.names = TRUE)
list.new.example <- list()
for (i in 1:3) {
   load(file.full[i])
list.new.example <- c(list.new.example, list.example)
}
print(list.new.example)

但这不是我想要的。 NULL 正在填充。非常感谢。

这种问题可以通过在单独的环境中加载每个文件来解决。然后只需从每个元素中提取名为 list.example 的元素并合并到一个列表中即可。

# Create the data
setwd(tempdir())
list.example <- list(1,2)
save(list.example, file="A.RData")
list.example <- list(NULL,NULL,3)
save(list.example, file="B.RData")
list.example <- list(NULL,NULL,NULL,4)
save(list.example, file="C.RData")

# Load
files <- c("A.RData", "B.RData", "C.RData")
env <- lapply(files, function(f){
    e <- new.env()
    load(f, envir=e)
    e
})

# Tidy up
l <- lapply(env, "[[", "list.example")
l <- unlist(l, recursive=FALSE)
list.new.example <- l[!sapply(l, is.null)]

环境属于 R 的高级功能,相对较少的用户熟悉。然而,它们非常容易理解并且非常有用,只需将它们视为无序的命名对象集,可以用与普通列表相同的方式进行操作。像这样

env[[1]]$list.example
env[[1]][["list.example"]]