constructing loops for calculating differences in r

If you have an ID for the pair of rows (like x4 in you example), you can use it to group_by.

Then you can do the difference of minimum and maximum time in that group, and assign it to rows that are the maximum time.

df %>% 
  group_by( x4 ) %>%
  mutate(difference = ifelse(time == max(time), max(time) - min(time), NA))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top