0

I am trying to generate lagged variable in R using the following code

  library(dpylr)
  dataretail<-dataretail %>%
      group_by(PERMNO) %>%
           mutate(newsheat_lag = lag(newsheat, n = 1,order_by = YYYYQ,default = NA)

but for some reason my lagged variable is identical to the original one. The same code used to work correctly a few months ago. Any idea what is going wrong?

Marius Zoican
  • 207
  • 1
  • 8
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jan 17 '23 at 18:13
  • 1
    Thanks! Managed to fix it eventually by using ```dplyr::lag``` instead of ```lag```. – Marius Zoican Jan 17 '23 at 18:14

1 Answers1

0

I would use data.table::shift() as I've find it to be more reliable.

mtcars$previousMPG<-data.table::shift(mtcars$mpg,1)
head(mtcars[,c(1,12)])
Ben
  • 1,113
  • 10
  • 26