【问题标题】:How can I remove elements by columns number from a list?如何从列表中按列号删除元素?
【发布时间】:2019-09-03 19:58:45
【问题描述】:

如果元素的数量小于 3,我想删除列表中的元素。

为此我尝试:

#Create a list

my_list <- list(a = c(3,5,6), b = c(3,1,0), c = 4, d = NA)
my_list

$a
[1] 3 5 6

$b
[1] 3 1 0

$c
[1] 4

$d
[1] NA

# Thant I create a function for remove the elements by my condition:

delete.F  <-  function(x.list){   
    x.list[unlist(lapply(x.list, function(x) ncol(x)) < 3)]}

delete.F(my_list)

我有输出:

Error in unlist(lapply(x.list, function(x) ncol(x)) < 3) : 
  (list) object cannot be coerced to type 'double'

有什么想法吗?

【问题讨论】:

    标签: r list function


    【解决方案1】:

    一种选择是使用lengths 创建一个逻辑表达式,并将其用于子集list

    my_list[lengths(my_list) >=3]
    #$a
    #[1] 3 5 6
    
    #$b
    #[1] 3 1 0
    

    请注意,在示例中,它是vectors 的list,而不是data.framelistncol/nrow 是当有 dim 属性时 - matrix 检查 TRUE,data.frame 也是如此


    如果我们想以某种方式使用lapply(基于一些约束),请使用length 创建逻辑

    unlist(lapply(my_list, function(x) if(length(x) >=3 ) x))
    

    如果我们需要使用lapply创建索引,请使用length(但会比lengths慢)

    my_list[unlist(lapply(my_list, length)) >= 3]
    

    【讨论】:

    • 不幸的是,我需要使用 unlist(lapply()) 而这个解决方案不起作用。
    • @Isabel 您的预期输出是什么?如果是list 的前两个元素,则此解决方案提供
    • @Isabel 您可以通过lapply查看更新的解决方案
    • @Isabel 如果你检查我的代码,我没有使用x.list[ 它只是unlist(lapply(.
    • @Isabel 如果你想获取索引my_list[unlist(lapply(my_list, length)) &gt;= 3]
    【解决方案2】:

    这里还有几个选项。在基础 R 中使用 Filter

    Filter(function(x) length(x) >=3, my_list)
    
    #$a
    #[1] 3 5 6
    
    #$b
    #[1] 3 1 0
    

    或者使用purrrkeepdiscard

    purrr::keep(my_list, ~length(.) >= 3)
    
    purrr::discard(my_list, ~length(.) < 3)
    

    【讨论】:

      猜你喜欢
      • 2020-03-14
      • 2021-03-10
      • 2015-08-14
      • 2010-10-12
      • 2022-12-23
      • 2010-10-13
      相关资源
      最近更新 更多