R - Combine arbitrary lists element by element wit

2019-07-20 14:22发布

I have two lists

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 )

Where the structure of m is:

List of 1
 $ a:List of 4
  ..$ b :List of 2
  .. ..$ : num 1
  .. ..$ : num 2
  ..$ c : num 3
  ..$ b1: num 4
  ..$ e : num 5

And the structure of n is:

List of 2
 $ a:List of 3
  ..$ b :List of 2
  .. ..$ : num 10
  .. ..$ : num 20
  ..$ c : num 30
  ..$ b1: num 40
 $ f: num 50

Want a combined output like this. Also the solution should be general for deeply nested lists.

Expected output :

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

Have seen this, but it is not general enough for deeply nested lists

R: Combining Nested List Elements by Name

标签: r
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-20 14:31

Here is a recursive way to do it:

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

In case you have multiple nested lists (m1, m2 and m3, for example) to merge, Reduce could be helpful:

Reduce(mergeList, list(m1, m2, m3))
查看更多
登录 后发表回答