如何为其余组创建前四个滞后的模式?

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

我当前的代码

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

我基本上有 1 个 属性(在本例中为酒店),测量时间超过 5 年,我正在尝试为所有组重新创建第一个模式

一种选择是使用 data.table

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