【问题标题】:Select column that has the fewest NA values选择具有最少 NA 值的列
【发布时间】:2018-05-23 20:04:46
【问题描述】:

我正在使用一个产生两个输出列的数据框。一列总是比另一列有更多的 NA 值,但不是以任何可预测的方式。这是我的问题,如何使用 dplyr 选择 NA 值最少的列。我正在考虑使用 which.min 来决定,但不知道如何将它们放在一起。请注意,两列都包含 na 值,我想选择这些值中最少的那一列。

【问题讨论】:

    标签: r select dplyr na


    【解决方案1】:

    您可以使用dplyr 和purrr 来做到这一点。

    在which.min 内部,您首先使用map 计算列中的NA 数(可以是您在data.frame 中的列数。keep 部分仅返回那些实际具有NA 的列。 which.min 返回命名向量,我们取其名称并将其提供给 dplyr 的 select 函数。

    我已经稍微概述了代码,以便您可以轻松查看哪些部分属于哪里。

    library(purrr)
    library(dplyr)
    
    
    df %>% select(names(which.min(df %>% 
                                    map(function(x) sum(is.na(x))) %>% 
                                    keep(~ .x > 0)
                                 )
                        )
                  )
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      
      df <- tibble(a = c(rep(c(NA, 1:5), 4)),      # df with different NA counts/col
                   b = c(rep(c(NA, NA, 2:5), 4)))
      
      
      
      df %>% 
        summarise_all(funs(sum(is.na(.))))         # NA counts
      #> # A tibble: 1 x 2
      #>       a     b
      #>   <int> <int>
      #> 1     4     8
      
      df %>%                                       # answer
        select_if(funs(which.min(sum(is.na(.)))))
      #> # A tibble: 24 x 1
      #>        a
      #>    <int>
      #>  1    NA
      #>  2     1
      #>  3     2
      #>  4     3
      #>  5     4
      #>  6     5
      #>  7    NA
      #>  8     1
      #>  9     2
      #> 10     3
      #> # ... with 14 more rows
      

      由reprex package (v0.2.0) 于 2018 年 5 月 25 日创建。

      【讨论】:

        猜你喜欢
        • 2017-10-20
        • 2019-02-09
        • 2015-12-05
        • 2021-12-03
        • 1970-01-01
        • 2021-07-23
        • 2021-08-25
        • 1970-01-01
        • 2017-11-20
        相关资源
        最近更新 更多