How would one keep the corresponding two rows (all columns preserved) that produced the max difference after grouping, arranging, and subtracting the 4th lead from the current value? I can currently use top_n to pluck out one row (see sample code below). Have easily used reframe to get the max difference after grouping, but keep the rows that produced that max is taking longer than expected. Thanks.
library(dplyr)
df %>%
group_by(group) %>%
arrange(DateTime)%>%
mutate(new_column = value- lead(value,n=4L)) %>%
top_n(1,new_column)
You are leading, which works by position, so you need to track positions, row_number() is good for that.
Here is an approach