【问题标题】:Filter rows of one column on the condition that rows in all other columns are NA, and repeat for n columns在所有其他列中的行都是NA的条件下过滤一列的行,并重复n列
【发布时间】:2020-06-10 15:02:06
【问题描述】:

如果之前有人问过这个问题,我们深表歉意;我不太确定如何表达这个问题,这可能会阻止其他问题出现在我的搜索中。

我的情况是我有一个这样的数据集:

toy <- 
  data.frame(
    Serves_1 = c("yes", NA, "yes", "no", "yes", "no"),
    Serves_2 = c(NA, NA, "no", "no", "no", "yes"),
    Serves_3 = c(NA, "no", "yes", "no", NA, "no"),
    Serves_4 = c(NA, "yes", "yes", "no", "yes", "no")
  )
toy

我正在尝试确定有多少行具有非 NA 的一列和所有其他列的 NA。以 Serves_1 列为例:

toy %>%
  filter(
    !is.na(Serves_1) &
      is.na(Serves_2) &
      is.na(Serves_3) &
      is.na(Serves_4)
  ) %>%
  nrow

有一行 Serves_1 具有非 NA 值,同时,所有其他列都具有该行的 NA。

此代码运行良好,但我需要对每一列重复此过程。我可以将每列的感叹号向下移动。但在我的真实数据集中,我必须对 20 多列执行此操作。

有没有更有效的方法来做到这一点(最好使用 dplyr)?

【问题讨论】:

    标签: r filter dplyr na


    【解决方案1】:

    你可以使用rowSums

    library(dplyr)
    toy <- 
      data.frame(
        Serves_1 = c("yes", NA, "yes", "no", "yes", "no"),
        Serves_2 = c(NA, NA, "no", "no", "no", "yes"),
        Serves_3 = c(NA, "no", "yes", "no", NA, "no"),
        Serves_4 = c(NA, "yes", "yes", "no", "yes", "no")
      ) %>% 
      mutate(na_sum = rowSums(is.na(.)))
    

    这给了你:

      Serves_1 Serves_2 Serves_3 Serves_4 na_sum
    1      yes     <NA>     <NA>     <NA>      3
    2     <NA>     <NA>       no      yes      2
    3      yes       no      yes      yes      0
    4       no       no       no       no      0
    5      yes       no     <NA>      yes      1
    6       no      yes       no       no      0
    

    然后,您可以过滤 na_sum == 3 的行,以获取其中一个值不为 NA 而其余为的所有行:

    toy %>% 
      filter(na_sum ==3)
    

    这给了我们:

      Serves_1 Serves_2 Serves_3 Serves_4 na_sum
    1      yes     <NA>     <NA>     <NA>      3
    

    【讨论】:

    • 这是一个非常聪明的解决方法,马特,谢谢!
    • 没问题!如果已解决您的问题,请考虑通过单击绿色复选标记将答案标记为完整。
    【解决方案2】:

    附加选项

    sum(apply(toy, 1, function(x) (length(x) - 1 == sum(is.na(x)))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-02
      • 2021-07-31
      • 2018-10-21
      • 2013-12-27
      • 2023-02-02
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      相关资源
      最近更新 更多