Combine different elements of the same list in different R workspaces

爱⌒轻易说出口 提交于 2019-12-12 03:25:33

问题


For example: Three R workspaces A.RData, B.RData and C.RData.

  • In A.RData: A list object list.example <- list(1,2)
  • In B.RData: The same name list object list.example <- list(NULL,NULL,3)
  • In C.RData: The same name list object list.example <- list(NULL,NULL,NULL,4)

What i want to get in a new workspace is an object list.new.example printed as:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]  
[1] 3  

[[4]]  
[1] 4

I have tried

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)

but it's not what i wanted. NULL is filling. So thanks.


回答1:


This kind of problem can be solved by loading each file in a separate environment. Then it's just a matter of extracting the element named list.example from each of them and combine in a list.

# 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)]

Environments belong to the more advanced features of R that relatively few users are familiar with. They are however quite simple to understand and very useful, just think of them as unordered sets of named objects, that can be manipulated in same ways as an ordinary list. Like this

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


来源:https://stackoverflow.com/questions/28088212/combine-different-elements-of-the-same-list-in-different-r-workspaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!