【问题标题】:Get same column by name using same code for two differently structured lists对两个不同结构的列表使用相同的代码按名称获取相同的列
【发布时间】:2020-07-08 03:25:56
【问题描述】:

我有两个结构不同的列表。在一个函数中,我想获得一个在两个列表中具有相同名称的列。有没有通用的方法来解决这个问题?

  list_1_1_1 <- list(list(list(tibble::tibble("a" = c(1, 2), "b"=c(3, 4))), list("a"=c(1, 2))))
  list_1_1_1
  # Call column called b
  list_1_1_1[[1]][[1]][[1]]$b

  
  list_1_1 <- list(list(tibble::tibble("a" = c(1, 2), "b"=c(3, 4))), list("a"=c(1, 2)))
  list_1_1
  # Call column called b
  list_1_1[[1]][[1]]$b

我想获得名为 b 的列,使用在两种不同情况/示例中工作的同一行代码,这可能吗? 提前致谢。

【问题讨论】:

  • 不确定我是否理解这个问题;这正是本示例中恰好调用该列的内容...

标签: r list


【解决方案1】:

可能是这样的。

foo <- function(l, pattern) {
  u <- unlist(l)
  unname(u[grep(pattern, names(u))])
}

foo(list_1_1_1, "b")
# 3 4

foo(list_1_1, "b")
# 3 4

【讨论】:

    【解决方案2】:

    使用外部包,我们可以使用 rrapply(base-rapply 的扩展以通过嵌套列表递归)开箱即用:

    library(rrapply)
    
    rrapply(list_1_1_1, condition = function(x, .xname) .xname == "b", how = "flatten")
    #> $b
    #> [1] 3 4
    rrapply(list_1_1, condition = function(x, .xname) .xname == "b", how = "flatten")
    #> $b
    #> [1] 3 4
    

    condition 参数决定返回哪些列表元素(在本例中为 data.frame 列),.xname 参数评估为正在评估的列表元素的名称(即列名)。

    相对于greps 元素基于unlist 构造的名称的函数的优点是我们可以避免任何意外行为:

    foo <- function(l, pattern) {
      u <- unlist(l)
      unname(u[grep(pattern, names(u))])
    }
    
    ## there are two 'a' columns, which are collapsed after unlisting the list
    foo(list_1_1_1, "a")
    #> [1] 1 2 1 2
    ## here the individual columns are still present
    rrapply(list_1_1_1, condition = function(x, .xname) .xname == "a", how = "flatten")
    #> $a
    #> [1] 1 2
    #> 
    #> $a
    #> [1] 1 2
    
    ## no 'a1' column is present in the data, but new names are assigned by unlist
    foo(list_1_1_1, "a1")
    #> [1] 1 1
    ## here no column is returned as expected
    rrapply(list_1_1_1, condition = function(x, .xname) .xname == "a1", how = "flatten")
    #> named list()
    

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多