Lag difference for a group in R

Hello friends! Today we’ll be learning to calculate the lag difference for a group in R.

install.packages("dplyr") 
library(dplyr) 

structure of the code will be as follows

data %>% group_by(column) %>% mutate(Diff = numCol - lag(numCol,N))
where N is the lag value 1,2,3...

example using iris dataset

iris %>% group_by(Species) %>% mutate(Diff = Petal.Width - lag(Petal.Width,4))

Keep visiting Analytics Tuts for more tutorials.

Thanks for reading! Comment your suggestions and queries


Leave a Reply

Your email address will not be published. Required fields are marked *