Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create lagged differences by group in R?

I have the following dataframe:

df <- data.frame(id = c("1", "1", "1", "2", "2"), 
                 x = c(12, 20, 24, 10, 14))

id   x
 1  12
 1  20
 1  24
 2  10
 2  14

I’d like to obain the lagged differences of x per id. The expected result:

id   x
 1  12
 1   8
 1   4
 2  10
 2   4

A dplyr solution is preferable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note that this question is not a duplicate, since the group refers to an ID in my case, not an unordered category.

>Solution :

Using diff

library(dplyr)

df %>% 
  mutate(x = c(x[1], diff(x)), .by = id)
  id  x
1  1 12
2  1  8
3  1  4
4  2 10
5  2  4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading