Search code examples
rlag

How can I create the pattern for the first four lags for the remaining groups?


Lag

My current code

GuestFirst_B$Lag_Loyal2 <- Lag(Loyal, shift = 1)
GuestFirst_B$Lag_Loyal1[which(!duplicated(GuestFirst_B$Property))] <- NA

GuestFirst_B$Lag_Loyal2 <- Lag(Loyal, shift = 2)
GuestFirst_B$Lag_Loyal2[which(!duplicated(GuestFirst_B$Property))] <- NA

GuestFirst_B$Lag_Loyal3 <- Lag(Loyal, shift = 3)
GuestFirst_B$Lag_Loyal3[which(!duplicated(GuestFirst_B$Property))] <- NA

GuestFirst_B$Lag_Loyal4 <- Lag(Loyal, shift = 4)
GuestFirst_B$Lag_Loyal4[which(!duplicated(GuestFirst_B$Property))] <- NA

I am basically having 1 property (in this case hotel) that is measured over 5 years and I am trying to recreate the first pattern for all groups


Solution

  • One option would be to use shift from data.table

    library(data.table)
    setDT(df1)[, paste0("Lag_Loyal", 1:4) := shift(Loyal, 1:4), by = grp]