2014-07-05 14 views
13

對於下面的數據如何刪除觀察組,dplyr ::過濾器()

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 ::過濾器()命令只保留不具有的ID單個NA?所以只有ID1和9的受試者應該留在過濾器之後。

+0

你的意思是1和9? –

回答

7

使用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 
+0

是的,1和9,我已經糾正它。謝謝@Robert Krzyzanowski,這正是我所需要的。我從來沒有見過以前用過的ave()函數,我很高興我問了一些,學到了一些新的東西。 – andrey

+0

謝謝!不要忘記註冊。 :) –

+0

我正在等待2分鐘通過接受它:)再次感謝! – andrey

28

或者你可以使用:

ds %>% 
group_by(id) %>% 
filter(attend=all(!is.na(attend))) 
#Source: local data frame [10 x 3] 
#Groups: id 

# 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 
+0

我更喜歡這個,因爲它保持在dplyr中,並且更短。謝謝! – andrey

+8

'sum(is.na(出席))== 0'也可以工作 – hadley

+0

感謝@hadley的評論。 – akrun