在不同的R工作区中合并同一列表的不同元素 [英] Combine different elements of the same list in different R workspaces
问题描述
例如:三个R工作区A.RData
,B.RData
和C.RData
.
For example: Three R workspaces A.RData
, B.RData
and C.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)
- In
A.RData
: A list objectlist.example <- list(1,2)
- In
B.RData
: The same name list objectlist.example <- list(NULL,NULL,3)
- In
C.RData
: The same name list objectlist.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
我尝试过
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
正在填充.所以谢谢.
but it's not what i wanted. NULL
is filling. So thanks.
推荐答案
可以通过将每个文件加载到单独的环境中来解决此类问题.然后,只需从每个元素中提取名为list.example
的元素并合并到一个列表中即可.
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)]
环境属于R的高级功能,相对很少的用户熟悉.但是,它们非常易于理解并且非常有用,只需将它们视为无序的命名对象集即可,可以按照与普通列表相同的方式对其进行操作.像这样
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"]]
这篇关于在不同的R工作区中合并同一列表的不同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!