Nathan
Nathan

Reputation: 97

How to get a data frame AFTER one matching a given condition?

Let's say I have data frame df below

> df <- data.frame(value=c(1001, 1002, 1001, 1006, 1003, 1001, 1005))
> df
  value
1  1001
2  1002
3  1001
4  1006
5  1003
6  1001
7  1005

And I want to perform some operation (say mean()) on all rows that immediately follow rows where value = 1001

My instinct was

 mean(df$value[(df$value==1001) +1])

But this did not work, and I'm not even sure how to describe what I'm trying to do well enough to Google it. I'm sure the solution is stupid simple. Thanks for any tips.

Upvotes: 2

Views: 42

Answers (1)

ngm
ngm

Reputation: 2589

You were close! Missing which, and in case the last row has value 1001 and you'd get NA for the next row (and also just in case there were NA elsewhere) you need na.rm = TRUE.

mean(df$value[which(df$value == 1001) + 1], na.rm = TRUE)

Upvotes: 1

Related Questions