R 有条件地从数据帧中删除行

R 有条件地从数据帧中删除行,r,R,如何有条件地从数据表中删除行 例如,我有: Apple, 2001 Apple, 2002 Apple, 2003 Apple, 2004 Banana, 2001 Banana, 2002 Banana, 2003 Candy, 2001 Candy, 2002 Candy, 2003 Candy, 2004 Dog, 2001 Dog, 2002 Dog, 2004 Water, 2002 Water, 2003 Water, 2004 然后,我只想包括每组2001-2004的行,即: A

如何有条件地从数据表中删除行

例如,我有:

Apple, 2001
Apple, 2002
Apple, 2003
Apple, 2004
Banana, 2001
Banana, 2002
Banana, 2003
Candy, 2001
Candy, 2002
Candy, 2003
Candy, 2004
Dog, 2001
Dog, 2002
Dog, 2004
Water, 2002
Water, 2003
Water, 2004
然后,我只想包括每组2001-2004的行,即:

Apple, 2001
Apple, 2002
Apple, 2003
Apple, 2004
Candy, 2001
Candy, 2002
Candy, 2003
Candy, 2004

使用
data.table
,检查
如果
所有2001:2004的数据都出现在%
每组“Col1”的“年份”列中,则获取数据子集。table

library(data.table)
setDT(df1)[, if(all(2001:2004 %in% year)) .SD, by = Col1]
#    Col1 year
#1: Apple 2001
#2: Apple 2002
#3: Apple 2003
#4: Apple 2004
#5: Candy 2001
#6: Candy 2002
#7: Candy 2003
#8: Candy 2004
数据
df1使用
base R
我们可以使用
ave
获得所需的结果

df[ave(df$year, df$Col1, FUN = function(x) all(2001:2004 %in% x)) == 1, ]

#   Col1 year
#1  Apple 2001
#2  Apple 2002
#3  Apple 2003
#4  Apple 2004
#8  Candy 2001
#9  Candy 2002
#10 Candy 2003
#11 Candy 2004

dplyr
进近:

library(dplyr) # or library(tidyverse)
df1 %>% 
    group_by(Col1) %>% 
    filter(all(2001:2004 %in% year))
%>%筛选器(TRUE)
返回所有行,而
%>%筛选器(FALSE)
删除所有数据行

输出:

Source: local data frame [8 x 2]
Groups: Col1 [2]

   Col1  year
  <chr> <int>
1 Apple  2001
2 Apple  2002
3 Apple  2003
4 Apple  2004
5 Candy  2001
6 Candy  2002
7 Candy  2003
8 Candy  2004
来源:本地数据帧[8 x 2]
分组:Col1[2]
一年级
1苹果2001
2苹果2002
3苹果2003
4苹果2004
5.2001年
6糖果2002
2003年7月7日
8糖果2004
Source: local data frame [8 x 2]
Groups: Col1 [2]

   Col1  year
  <chr> <int>
1 Apple  2001
2 Apple  2002
3 Apple  2003
4 Apple  2004
5 Candy  2001
6 Candy  2002
7 Candy  2003
8 Candy  2004