从不平衡到平衡面板 [英] From Unbalanced to Balanced Panel

查看:273
本文介绍了从不平衡到平衡面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在一个组内填充缺少的行,其中一个组由特定的(id1,id2)定义。

I wand to fill in missing rows within a group, where a group is defined by a specific (id1,id2).

例如我有一个数据集

  id1   id2  year  value
  33    29  1990     3.5
  33    29  1993     3.3
  33    29  1994     3.1
  32    28  1992     3.1
  32    28  1993     4.5

以获取以下数据集

 id1   id2  year   value
  33    29  1990     3.5
  33    29  1991      NA
  33    29  1992      NA
  33    29  1993     3.3
  33    29  1994     3.1
  32    28  1992     3.1
  32    28  1993     4.5

请注意,不需要创建 year == 1991,year == 1992 为第二组。示例是简化的,但是解决方案应该适用于字符串/数字,以及几个值列而不是一个。

Note that row with year==1991,year==1992 does not need to be created for the second group. The example is simplified, but the solution should work for strings/numerics, and for several value columns instead of just one.

推荐答案

如何?

require(data.table)
DT = data.table(id1 = c(33,33,33,32,32),
                id2 = c(29,29,29,28,28),  
               year = c(1990,1993,1994,1991,1992),
              value = c(3.5,3.3,3.1,3.1,4.5))


setkey(DT, id1,id2,year)
ans = DT[, list(year = seq.int(year[1L], year[.N])), by = list(id1,id2)]
ans = DT[setkey(ans)]
#    id1 id2 year value
# 1:  32  28 1991   3.1
# 2:  32  28 1992   4.5
# 3:  33  29 1990   3.5
# 4:  33  29 1991    NA
# 5:  33  29 1992    NA
# 6:  33  29 1993   3.3
# 7:  33  29 1994   3.1

这篇关于从不平衡到平衡面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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