使用dplyr过滤数据帧

时间:2015-01-30 21:48:41

标签: r dplyr

我有这个data.frame:

df <- data.frame(
    id = c("x1", "x2", "x3", "x4", "x5", "x1", "x2", "x6", "x7", "x8", "x7", "x8" ), 
    age = c(rep("juvenile", 5), rep("adult", 7))
    )
df 

   id      age
1  x1 juvenile
2  x2 juvenile
3  x3 juvenile
4  x4 juvenile
5  x5 juvenile
6  x1    adult
7  x2    adult
8  x6    adult
9  x7    adult
10 x8    adult
11 x7    adult
12 x8    adult

每行代表一个人。我想拉出所有成年人再次看到青少年的行。我不希望最初看到成年人的行再次成为成年人(ids x7和x8)。因此得到的data.frame应为:

  id      age
1 x1 juvenile
2 x2 juvenile
3 x1    adult
4 x2    adult

我专注于dplyr解决方案。

3 个答案:

答案 0 :(得分:6)

您可以按id进行分组,只选择那些同时包含“青少年”和“成年人”的群组:

df %>% 
   group_by(id) %>% 
   filter(all(c('juvenile','adult') %in% age))

#Source: local data frame [4 x 2]
#Groups: id
#
#  id      age
#1 x1 juvenile
#2 x2 juvenile
#3 x1    adult
#4 x2    adult

答案 1 :(得分:4)

以下是使用dplyr的等解决方案,在寻找更具体的阈值时可能会有用:

df %>% 
  group_by(id) %>% 
  filter(sum(age == 'juvenile') >= 1 & sum(age == 'adult') >= 1)

# Source: local data frame [4 x 2]
# Groups: id
# 
# id      age
# 1 x1 juvenile
# 2 x2 juvenile
# 3 x1    adult
# 4 x2    adult

答案 2 :(得分:2)

嘿,我认为这是你正在寻找的......为了展示而将其分解,但我确信你可以通过不重新分配过滤器的结果来使它更紧凑参数。

kids <- df %>%
  filter(age == "juvenile")

adults <- df %>%
  filter(age == "adult")

repeat_offender<-inner_join(kids,adults, by = "id")
repeat_offender

按要求实际返回答案......

this_solution_sucks<-gather(repeat_offender, agex, age, -id) %>% select(-agex)