使用 group_by 过滤特定案例,同时保留 NA

Use group_by to filter specific cases while keeping NAs

我想过滤我的数据集以将具有观察结果的个案保留在特定列中。举例说明:

help <- data.frame(deid = c(5, 5, 5, 5, 5, 12, 12, 12, 12, 17, 17, 17),
               score.a = c(NA, 1, 1, 1, NA, NA, NA, NA, NA, NA, 1, NA))

创建

   deid score.a
1     5      NA
2     5       1
3     5       1
4     5       1
5     5      NA
6    12      NA
7    12      NA
8    12      NA
9    12      NA
10   17      NA
11   17       1
12   17      NA

我想告诉 dplyr 保留在 score.a 中有任何观察结果的案例,包括 NA 值。因此,我希望它 return:

  deid score.a
1     5      NA
2     5       1
3     5       1
4     5       1
5     5      NA
6    17      NA
7    17       1
8    17      NA

I 运行 代码 help %>% group_by(deid) %>% filter(score.a > 0) 但是它也会提取 NA。感谢您的帮助。

编辑:这里问了一个类似的问题 How to remove groups of observation with dplyr::filter() 但是,在答案中他们使用 'all' 条件,这需要使用 'any' 条件。

尝试

library(dplyr)
help %>%
      group_by(deid) %>%
      filter(any(score.a >0 & !is.na(score.a)))
#    deid score.a
#1    5      NA
#2    5       1
#3    5       1
#4    5       1
#5    5      NA
#6   17      NA
#7   17       1
#8   17      NA

或与 data.table

类似的方法
library(data.table)
setDT(help)[, if(any(score.a>0 & !is.na(score.a))) .SD , deid]
#    deid score.a
#1:    5      NA
#2:    5       1
#3:    5       1
#4:    5       1
#5:    5      NA
#6:   17      NA
#7:   17       1
#8:   17      NA

如果条件是用'score.a'中的所有值对'deid's进行子集化>0,那么上面的代码可以修改为,

setDT(help)[,  if(!all(is.na(score.a)) & 
         all(score.a[!is.na(score.a)]>0)) .SD , deid]
#   deid score.a
#1:    5      NA
#2:    5       1
#3:    5       1
#4:    5       1
#5:    5      NA
#6:   17      NA
#7:   17       1
#8:   17      NA

假设'deid'组中的'score.a'之一小于0,

help$score.a[3] <- -1

上面的代码会return

 setDT(help)[,  if(!all(is.na(score.a)) & 
           all(score.a[!is.na(score.a)]>0, deid],
 #   deid score.a
 #1:   17      NA
 #2:   17       1
 #3:   17      NA
library(dplyr)
df%>%group_by(deid)%>%filter(sum(score.a,na.rm=T)>0)