Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a dataframe with dplyr

Tags:

r

dplyr

I have this 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

Each row represents an individual. I want to pull out all rows where juveniles were seen again as adults. I do not want rows where individuals originally seen a adults were seen again as adults (ids x7 and x8). So the resultant data.frame should be this:

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

I'm specifically after a dplyr solution.

like image 791
luciano Avatar asked Sep 02 '26 13:09

luciano


1 Answers

You can group by id and select only those groups that contain both 'juvenile' and 'adult':

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
like image 64
Marat Talipov Avatar answered Sep 04 '26 03:09

Marat Talipov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!