tcash21
tcash21

Reputation: 4995

Extract rows according to consecutive value pattern from data.frame

I have a data.frame, d:

d<-data.frame(id=c(1,1,1,1,2,2,3,3,3,3), var=c("no", "no", "no", "yes", "no", "yes", "no", "yes", "yes", "yes"))

I'd like to return all "no" rows for each ID leading up to a "yes" and including the first "yes".

desired result:

id var
1  no
1  no
1  no
1 yes
2  no
2 yes
3  no
3 yes

Upvotes: 1

Views: 372

Answers (1)

Matthew Plourde
Matthew Plourde

Reputation: 44614

As @joran indicates, it's polite to include what you've tried. It also increases the likelihood your question will get votes. This question is basic enough that even a rudimentary understanding of R could arrive at something.

In any case, this will do what you want:

d[! duplicated(d) | d$var == 'no', ]

Upvotes: 2

Related Questions