这是一种递归方法:
mergeList <- function(x, y){
if(is.list(x) && is.list(y) && !is.null(names(x)) && !is.null(names(y))){
ecom <- intersect(names(x), names(y))
enew <- setdiff(names(y), names(x))
res <- x
if(length(enew) > 0){
res <- c(res, y[enew])
}
if(length(ecom) > 0){
for(i in ecom){
res[i] <- list(mergeList(x[[i]], y[[i]]))
}
}
return(res)
}else{
return(c(x, y))
}
}
m = list( 'a' = list( 'b' = list( 1, 2 ), 'c' = 3, 'b1' = 4, 'e' = 5 ) )
n = list( 'a' = list( 'b' = list( 10, 20 ), 'c' = 30, 'b1' = 40 ), 'f' = 50 )
mn <- mergeList(m, n)
str(mn)
# List of 2
# $ a:List of 4
# ..$ b :List of 4
# .. ..$ : num 1
# .. ..$ : num 2
# .. ..$ : num 10
# .. ..$ : num 20
# ..$ c : num [1:2] 3 30
# ..$ b1: num [1:2] 4 40
# ..$ e : num 5
# $ f: num 50
如果您有多个嵌套列表(m1
, m2
and m3
,例如)合并,Reduce
可能会有帮助:
Reduce(mergeList, list(m1, m2, m3))