【问题标题】:Remove NA from list of list and preserve structure in R从列表列表中删除 NA 并保留 R 中的结构
【发布时间】:2021-03-15 16:52:12
【问题描述】:

这是我的例子。

test <- list(el_1 = data.frame(col_1 = c(1,2), col_2 = c(2,3)), el_2 = NA)

我想删除列表的第二个元素。

这是我尝试过的。

test_1 <- sapply(test, function(x) x[!is.na(x)], simplify = F)
test_2 <- sapply(test, function(x) !is.na(x), simplify = F)
test_3 <- unlist(test) 

它们都不起作用,在每种情况下,我的数据框都被转换为字符串。

【问题讨论】:

    标签: r list na


    【解决方案1】:

    这行得通吗:

    test[!sapply(test, function(x) all(is.na(x)))]
    $el_1
      col_1 col_2
    1     1     2
    2     2     3
    

    【讨论】:

      【解决方案2】:

      一种方法可以是:

      #Code
      test[-which(names(test) %in% names(which(is.na(unlist(test)))))]
      

      【讨论】:

        【解决方案3】:

        我们可以在base R中使用Filter

        Filter(function(x) any(!is.na(x)), test)
        #$el_1
        #  col_1 col_2
        #1     1     2
        #2     2     3
        

        或者使用keep 来自purrr

        library(purrr)
        keep(test, ~ any(!is.na(.x)))
        #$el_1
        #  col_1 col_2
        #1     1     2
        #2     2     3
        

        【讨论】:

        • 我猜这里的关键是any
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-22
        • 2017-07-10
        相关资源
        最近更新 更多