0

I have a large dataset with this form:

df <- data.frame(event = c("request","request","response", "request"), 
      value = 1:4)
event      value
request     1
request     2
response    3
request     4

I'd like write to next_different_event_value, the value in the row with next different event. Desired output:

event      value    next_different_event_value
request     1       3
request     2       3
response    3       4
request     4       NA

Ideally, I can do this with tidyverse approach and without joins.

Thanks.

1
  • For more context, my actual value column is timestamp data. Commented Dec 27, 2018 at 17:47

1 Answer 1

3

A dplyr solution:

df %>%
 mutate(next_different_event_value = ifelse(event != lead(event), lead(value), NA)) %>%
 fill(next_different_event_value, .direction = "up")

     event value next_different_event_value
1  request     1                          3
2  request     2                          3
3 response     3                          4
4  request     4                         NA

It compares whether the "event" is the same as the next "event" row. If not, it assigns the value from the next "event" row, otherwise it assigns NA. Then, it fills the missing values with the last non-NA value from down to up.

Sign up to request clarification or add additional context in comments.

1 Comment

this solved the underlying problem for me: github.com/robinsones/funneljoin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.