R - 根据匹配的名称逐个元素组合任意列表

2024-02-05

我有两个清单

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 )

其中 m 的结构为:

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

n的结构为:

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

想要这样的组合输出。此外,该解决方案对于深度嵌套列表应该是通用的。

预期输出:

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

见过这个,但对于深度嵌套列表来说它不够通用

R:按名称组合嵌套列表元素 https://stackoverflow.com/questions/33395041/r-combining-nested-list-elements-by-name


这是一种递归方法:

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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R - 根据匹配的名称逐个元素组合任意列表 的相关文章

随机推荐