Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter to remove all rows before the first time a particular value in a specific column appears

Tags:

r

I would like to filter to remove all rows before the first time a particular value in a specific column appears. For example, in the data frame below, I would like to remove all rows before bob appears in column a for the first time. Please note that the value of bob repeats a second time -I only want to remove the rows before the first time bob appears.

(dat<-data.frame(a= c("pete", "mike", "bob", "bart", "bob"), b=c(1,2,3,4,5), c=c("home", "away", "home", "away", "gone")))
     a b    c
1 pete 1 home
2 mike 2 away
3  bob 3 home
4 bart 4 away
5  bob 5 gone

I want the resulting data frame to look like the following:

   a   b  c
1 bob  3 home
2 bart 4 away
3 bob  5 gone
like image 341
Cyrus Mohammadian Avatar asked Apr 11 '19 07:04

Cyrus Mohammadian


2 Answers

dplyr way using slice.

library(dplyr)
dat %>% slice(which.max(a == "bob") : n())

#     a b    c
#1  bob 3 home
#2 bart 4 away
#3  bob 5 gone

which in base R would be

dat[which.max(dat$a == "bob") : nrow(dat), ]
like image 167
Ronak Shah Avatar answered Sep 27 '22 19:09

Ronak Shah


cumsum is usually a good candidate for such tasks

dat[cumsum(dat$a == "bob") >= 1, ]
#     a b    c
#3  bob 3 home
#4 bart 4 away
#5  bob 5 gone
like image 44
markus Avatar answered Sep 27 '22 19:09

markus