0

我想定义一个函数 lag_and_dummies 它将为我的数据添加 2 个滞后以及 3 级虚拟变量(记住如何将它们正确地包含在面板数据中)。

让我们考虑数据:

data("EmplUK", package="plm")
head(EmplUK)
  firm year sector   emp    wage capital   output
1    1 1977      7 5.041 13.1516  0.5894  95.7072
2    1 1978      7 5.600 12.3018  0.6318  97.3569
3    1 1979      7 5.015 12.8395  0.6771  99.6083
4    1 1980      7 4.715 13.8039  0.6171 100.5501
5    1 1981      7 4.093 14.2897  0.5076  99.5581
6    1 1982      7 3.166 14.8681  0.4229  98.6151

功能

lag_and_dummies <- function(x) {
  #adding 2 lags to wage
  x <- x %>%
    group_by_at(1) %>%
    mutate(across(wage, dplyr::lag, n = 2, default = NA))
  #deleting NA's
  x <- na.omit(x)
  #creating dummy three-level dummy variables
  x <- within(x, {
    dummy <- as.factor(ave(get(colnames(x)[2]), get(colnames(x)[1]), FUN = function(a) rep_len(1:3, length(a))))
  })
  x <- cbind(x, model.matrix(~ dummy - 1, data = x))
  x
}

发生的奇怪事情是虚拟变量的三列存储在一列中。看看查看输出:

在此处输入图像描述

但是,如果我从 lag_and_dummies 中删除添加滞后,它可以正常工作,即

lag_and_dummies <- function(x) {
  x <- within(x, {
    dummy <- as.factor(ave(get(colnames(x)[2]), get(colnames(x)[1]), FUN = function(a) rep_len(1:3, length(a))))
  })
  x <- cbind(x, model.matrix(~ dummy - 1, data = x))
  x
}

在此处输入图像描述

您知道为什么包含滞后会导致在一列中创建虚拟变量吗?

4

1 回答 1

0

在您的第一个函数中,您的数据被分组。当 cbind 带有分组 tibble 的数据框时似乎存在一些问题。您可以ungroup获取数据并且它按预期工作。

library(dplyr)

lag_and_dummies <- function(x) {
  x <- x %>%
    group_by_at(1) %>%
    mutate(wage = dplyr::lag(wage, n = 2, default = NA))
  x <- na.omit(x)
  #creating dummy three-level dummy variables
  x <- within(x, {
    dummy <- as.factor(ave(get(colnames(x)[2]), 
             get(colnames(x)[1]), FUN = function(a) rep_len(1:3, length(a))))
  })
  x <- cbind(x %>% ungroup, model.matrix(~ dummy - 1, data = x))
  x
}

lag_and_dummies(EmplUK)
于 2020-12-03T10:57:05.127 回答