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

时间:2015-01-22 11:58:02

标签: r list rdata

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

  • A.RData:列表对象list.example <- list(1,2)
  • B.RData中:相同的名称列表对象list.example <- list(NULL,NULL,3)
  • C.RData中:相同的名称列表对象list.example <- list(NULL,NULL,NULL,4)

我希望在新工作区中获得的是一个对象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正在填补。谢谢。

1 个答案:

答案 0 :(得分:1)

通过在单独的环境中加载每个文件,可以解决此类问题。然后,只需从每个元素中提取名为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"]]