r-复制平衡面板的年度全州值



我正在尝试将今年的总值复制到下一年的值。我的数据集如下:

x1x2//tr><1><2>2025
2000 德克萨斯州
2000 NY 3 4。
2010德克萨斯州 10
2010 NY 30 40
2020德克萨斯州 15
2020 NY 35 45

根据stateyear组,如果年份<2020年,然后重新排列年份:

library(data.table)
f <- function(n,d) d[rep(1,n)]
setDT(df)[, f(fifelse(.BY$year<2020,10,1), .SD),.(state,year)][
,year:=seq(min(year),by=1,length.out=.N),state][]

输出:

<char> <int> <int> <num>
1:  Texas  2000     1     2
2:  Texas  2001     1     2
3:  Texas  2002     1     2
4:  Texas  2003     1     2
5:  Texas  2004     1     2
6:  Texas  2005     1     2
7:  Texas  2006     1     2
8:  Texas  2007     1     2
9:  Texas  2008     1     2
10:  Texas  2009     1     2
11:     NY  2000     3     4
12:     NY  2001     3     4
13:     NY  2002     3     4
14:     NY  2003     3     4
15:     NY  2004     3     4
16:     NY  2005     3     4
17:     NY  2006     3     4
18:     NY  2007     3     4
19:     NY  2008     3     4
20:     NY  2009     3     4
21:  Texas  2010    10    20
22:  Texas  2011    10    20
23:  Texas  2012    10    20
24:  Texas  2013    10    20
25:  Texas  2014    10    20
26:  Texas  2015    10    20
27:  Texas  2016    10    20
28:  Texas  2017    10    20
29:  Texas  2018    10    20
30:  Texas  2019    10    20
31:     NY  2010    30    40
32:     NY  2011    30    40
33:     NY  2012    30    40
34:     NY  2013    30    40
35:     NY  2014    30    40
36:     NY  2015    30    40
37:     NY  2016    30    40
38:     NY  2017    30    40
39:     NY  2018    30    40
40:     NY  2019    30    40
41:  Texas  2020    15    25
42:     NY  2020    35    45
state  year    x1    x2

相关内容

  • 没有找到相关文章

最新更新