【问题标题】:Subsetting row if NA is present if there is more than one occurance of another variable of interest?如果另一个感兴趣的变量不止一次出现,则如果存在 NA 则子集行?
【发布时间】:2019-01-28 16:44:33
【问题描述】:
   Indicator Name Examine
1           Alpha      NA
2            Beta    2013
3            Beta    2017
4            Beta      NA
5         Charlie    2013
6         Charlie    2017
7         Charlie      NA
8           Delta    2016
9            Echo    2016
10           <NA>      NA
11           <NA>      NA
12        Foxtrot    2007
13        Foxtrot      NA

在这里,我想删除Examine 中存在NA 的行,如果Indicator Name 有多个条目,除了NA

因此,第 4、7 和 13 行将被删除。

样本df:

structure(list(`Indicator Name` = c("Alpha", "Beta", "Beta", 
"Beta", "Charlie", "Charlie", "Charlie", "Delta", "Echo", NA, 
NA, "Foxtrot", "Foxtrot"), Examine = c(NA, 2013, 2017, NA, 2013, 
2017, NA, 2016, 2016, NA, NA, 2007, NA)), row.names = c(NA, 13L
), class = "data.frame")

【问题讨论】:

    标签: r dplyr subset


    【解决方案1】:

    在按“指标名称”分组后,在filter 中创建一个条件以删除 NA 元素或保留 all 元素是否为 NA

    library(dplyr)
    df %>% 
       group_by(`Indicator Name`) %>%
       filter(!is.na(Examine)| all(is.na(Examine)))
    

    或者在base R中使用同样的逻辑

    df[with(df, ave(is.na(Examine), `Indicator Name`, FUN = function(x) !x|all(x))),]
    

    【讨论】:

    • all(is.na()) 在这段代码中如何工作?更具体地说,为什么is.na(Examine) 不够?
    • @NelsonGon。只有在“检查”中有非 NA 元素时,OP 才想删除 NA 元素,因此代码的第一位就是 !is.na(Examine),但这也将删除所有元素都是 NA 的情况。为避免这种情况,请包含 OR 条件以使这些组在“检查”中保留所有 NA 元素
    • 啊,我明白了。谢谢。我已经忘记了分组位。再次感谢!
    猜你喜欢
    • 2014-02-21
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2013-08-02
    • 1970-01-01
    • 2015-07-16
    相关资源
    最近更新 更多