Calculate difference in date by indicator variable

Viewed 20

Suppose I have the following example dataframe with each id observation containing 1 group 1 observation (reference value):

id  date             group
1   15-01-2022        1
1   15-01-2022        2
1   16-01-2022        2
1   20-01-2022        2
2   18-01-2022        1
2   20-01-2022        2
2   27-01-2022        2

I want to calculate a column for the difference between each date for ids in group 1 vs group 2:

id  date             group  diff
1   15-01-2022        1      NA
1   15-01-2022        2      0
1   16-01-2022        2      1
1   20-01-2022        2      5
2   18-01-2022        1      NA
2   20-01-2022        2      2
2   27-01-2022        2      9
1 Answers
library(dplyr)
df %>% 
  group_by(id) %>%
  mutate(diff = date - date[group == 1]) %>%
  ungroup()

This assumes your date is already of class Date. It will put a 0 rather than a NA for the first value. If you need the NA then you can instead use:

df %>% 
  group_by(id) %>%
  mutate(diff = ifelse(group == 1, NA, date - date[group == 1])) %>%
  ungroup()
Related