2

df:

ID     cat1
A0001   358
A0001   279
A0049   324
A0049   358
A0049   432

To calculate the difference in value in cat1 between the repeated measures (by ID). The expected output df should look like:

 ID    cat1 cat1_diff
A0001   358   NA
A0001   279   -79
A0049   324   NA
A0049   358   26
A0049   432   74

I would appreciate any insights how to do this in R.

sleepyjoe
  • 267
  • 1
  • 2
  • 11

1 Answers1

2

We can use dplyr, and the lag function:

library(dplyr)
df %>% group_by(ID) %>%
       mutate(cat1_diff = cat1 - lag(cat1))

Source: local data frame [5 x 3]
Groups: ID

     ID cat1 cat1_diff
1 A0001  358        NA
2 A0001  279       -79
3 A0049  324        NA
4 A0049  358        34
5 A0049  432        74
jeremycg
  • 24,657
  • 5
  • 63
  • 74