我想为我的月度面板数据创建滞后变量。我的示例数据集如下所示。如何在year_month面板数据中生成滞后变量
Time ID Value1
Jan-14 A 12
Feb-14 A 14
Mar-14 A 15
Apr-14 A 18
May-14 A 10
Jun-14 A 12
Jul-14 A 13
Aug-14 A 14
Jan-14 B 32
Feb-14 B 14
Mar-14 B 15
Apr-14 B 18
May-14 B 20
Jun-14 B 12
Jul-14 B 13
Aug-14 B 14
我想为每个ID创建2个新的lag-1和lag-1变量。我做了类似于下面的内容,但它仅适用于ID:A,而其余ID则采用先前ID的滞后。
library(zoo)
library(plm)
df["Time1"] <- as.yearmon(df$Time,format="%b-%y")
pdf1 <-pdata.frame(df,index=c("ID","Time1"))
pdf1$lag1_Value1<-lag((pdf1$Value1), 1)
但我理想的需要我的输出如下。
Time ID Value1 lag1.Value1 lag2_Value1
Jan-14 A 12 NA NA
Feb-14 A 14 12 NA
Mar-14 A 15 14 12
Apr-14 A 18 15 14
May-14 A 10 18 15
Jun-14 A 12 10 18
Jul-14 A 13 12 10
Aug-14 A 14 13 12
Jan-14 B 32 NA NA
Feb-14 B 14 32 NA
Mar-14 B 15 14 32
Apr-14 B 18 15 14
May-14 B 20 18 15
Jun-14 B 12 20 18
Jul-14 B 13 12 20
Aug-14 B 14 13 12
我的示例数据集在下面的代码中给出。
df=structure(list(Time = structure(c(4L, 3L, 7L, 1L, 8L, 6L, 5L,
2L, 4L, 3L, 7L, 1L, 8L, 6L, 5L, 2L), .Label = c("Apr-14", "Aug-14",
"Feb-14", "Jan-14", "Jul-14", "Jun-14", "Mar-14", "May-14"), class ="factor"),
ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"),
Value1 = c(12L, 14L, 15L, 18L, 10L, 12L, 13L, 14L, 32L, 14L,
15L, 18L, 20L, 12L, 13L, 14L), Time1 = structure(c(2014,
2014.08333333333, 2014.16666666667, 2014.25, 2014.33333333333,
2014.41666666667, 2014.5, 2014.58333333333, 2014, 2014.08333333333,
2014.16666666667, 2014.25, 2014.33333333333, 2014.41666666667,
2014.5, 2014.58333333333), class = "yearmon")), row.names = c(NA,
-16L), .Names = c("Time", "ID", "Value1", "Time1"), class = "data.frame")
感谢您的任何帮助。
这两个答案的给定示例数据集在这里工作的序列。但只有data.table解决方案适用于我的实际数据集。 – sriya