如何使用dplyr :: filter()删除观察组 [英] How to remove groups of observation with dplyr::filter()

查看:124
本文介绍了如何使用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?所以只有具有ids 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.

推荐答案

使用过滤器 :: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆