在 R 中的不平衡面板数据中创建滞后变量 [英] Create lagged variable in unbalanced panel data in R

查看:46
本文介绍了在 R 中的不平衡面板数据中创建滞后变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个变量,其中包含一个组中前一年的变量值.

I'd like to create a variable containing the value of a variable in the previous year within a group.

     id   date        value
1     1   1992          4.1  
2     1     NA          4.5  
3     1   1991          3.3  
4     1   1990          5.3  
5     1   1994          3.0  
6     2   1992          3.2  
7     2   1991          5.2  

value_lagged 在组中缺少前一年时应该丢失 - 因为它是组中的第一个日期(如第 4、7 行),或者因为在数据(如第 5 行).此外,当缺少当前时间(如第 2 行)时,应该缺少 value_lagged.

value_lagged should be missing when the previous year is missing within a group - either because it is the first date within a group (as in row 4, 7), or because there are year gaps in the data (as in row 5). Also, value_lagged should be missing when the current time is missing (as in row 2).

这给出:

     id   date    value    value_lagged  
1     1   1992      4.1             3.3
2     1     NA      4.5              NA
3     1   1991      3.3             5.3
4     1   1990      5.3              NA
5     1   1994      3.0              NA
6     2   1992      3.2             5.2
7     2   1991      5.2              NA

<小时>

现在,在 R 中,我使用 data.table

 DT = data.table(id    = c(1,1,1,1,1,2,2),
                 date  = c(1992,NA,1991,1990,1994,1992,1991),
                 value = c(4.1,4.5,3.3,5.3,3.0,3.2,5.2)
                )
 setkey(DT, id, date)
 DT[, value_lagged := DT[J(id, date-1), value], ]
 DT[is.na(date), value_lagged := NA, ]

它很快,但对我来说似乎有点容易出错.我想知道是否有使用 data.tabledplyr 或任何其他包的更好的替代方案.非常感谢!

It's fast but it seems somewhat error prone to me. I'd like to know if there are better alternatives using data.table, dplyr, or any other package. Thanks a lot!

Stata 中,你会这样做:

In Stata, one would do:

    tsset id date
    gen value_lagged=L.value

推荐答案

使用tlag 组内定义的函数id

library(dplyr)
tlag <- function(x, n = 1L, time) { 
  index <- match(time - n, time, incomparables = NA)
  x[index]
}

df %>% group_by(id) %>% mutate(value_lagged = tlag(value, 1, time = date))

这篇关于在 R 中的不平衡面板数据中创建滞后变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆