如何使用 dplyr::filter() 删除观察组 [英] How to remove groups of observation with dplyr::filter()
本文介绍了如何使用 dplyr::filter() 删除观察组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下数据
ds <- read.table(header = TRUE, text ="
id year attend
1 2007 1
1 2008 1
1 2009 1
1 2010 1
1 2011 1
8 2007 3
8 2008 NA
8 2009 3
8 2010 NA
8 2011 3
9 2007 2
9 2008 3
9 2009 3
9 2010 5
9 2011 5
10 2007 4
10 2008 4
10 2009 2
10 2010 NA
10 2011 NA
")
ds<- ds %>% dplyr::mutate(time=year-2000)
print(ds)
我将如何编写 dplyr::filter() 命令以仅保留没有单个 NA 的 ID?因此,只有 ID 为 1 和 9 的主题才应留在过滤器之后.
How would I write a dplyr::filter() command to keep only the ids that don't have a single NA? So only subjects with ids 1 and 9 should stay after the filter.
推荐答案
使用 filter
和 base::ave
ds %>% dplyr::filter(ave(!is.na(attend), id, FUN = all))
获取
id year attend
1 1 2007 1
2 1 2008 1
3 1 2009 1
4 1 2010 1
5 1 2011 1
6 9 2007 2
7 9 2008 3
8 9 2009 3
9 9 2010 5
10 9 2011 5
这篇关于如何使用 dplyr::filter() 删除观察组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文