Cyrus Mohammadian
Cyrus Mohammadian

Reputation: 5193

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

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

Upvotes: 6

Views: 1518

Answers (3)

akrun
akrun

Reputation: 886998

We can use cummax

library(dplyr)
dat %>%
     filter(cummax(a == "bob") > 0)
#     a b    c
#1  bob 3 home
#2 bart 4 away
#3  bob 5 gone

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388862

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), ]

Upvotes: 10

markus
markus

Reputation: 26343

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

Upvotes: 5

Related Questions