【发布时间】:2021-07-03 04:09:59
【问题描述】:
让我们考虑以下数据集:
library(plm)
data("EmplUK", package = 'plm')
df <- EmplUK[1:6]
head(df)
> head(df)
firm year sector emp wage capital
1 1 1977 7 5.041 13.1516 0.5894
2 1 1978 7 5.600 12.3018 0.6318
3 1 1979 7 5.015 12.8395 0.6771
4 1 1980 7 4.715 13.8039 0.6171
5 1 1981 7 4.093 14.2897 0.5076
6 1 1982 7 3.166 14.8681 0.4229
如您所见,它是基本面板数据。现在我想对这个数据集应用滞后,但我当然不想对公司和年份应用滞后。
现在让我们将滞后向量定义为lags <- c(2,1,3,0)。这意味着:
(1) 扇区的两个滞后(数据帧中的第三个变量)
(2) emp 有一个滞后(数据框中的第四个变量)
(3) 工资的三个滞后(数据框中的第五个变量)
(4) 资本零滞后(数据框中的第六个变量)
当然,对于面板数据的约定,必须应用滞后 - 即包括每个周期开始时的滞后。
我的解决方案
for (i in seq_len(length(lags))) {
# Filter our data and apply lags for each time period
df <- df %>%
dplyr::group_by_at(1) %>%
# Take only those observations which amount
# is bigger than maximum number of lags
dplyr::filter(n() > max(lags)) %>%
dplyr::mutate(dplyr::across(
colnames(df)[i + 2], dplyr::lag,
n = lags[i], default = NA
))
}
> head(df)
> head(df)
# A tibble: 6 x 6
# Groups: firm [1]
firm year sector emp wage capital
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1977 NA NA NA 0.589
2 1 1978 NA 5.04 NA 0.632
3 1 1979 7 5.60 NA 0.677
4 1 1980 7 5.01 13.2 0.617
5 1 1981 7 4.72 12.3 0.508
6 1 1982 7 4.09 12.8 0.423
但是,尽管它可以工作,但我发现它很不方便 - 我使用循环来完成它,但我确定在那里没有必要。你能帮我重写我做过但没有循环的代码吗?
【问题讨论】: