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
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), ]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With