面板数据 - 按组求和并创建新变量

时间:2017-08-25 13:25:26

标签: r sum panel-data

我知道已经有很多关于“按组加总”的问题,但是,我没有解决我的问题。这是它:

df1是我的简化数据集

> df1 = data.table( Year = c(2009,2009,2009,2009,2009,2009,2009,2009,2010,2010,2010,2010),
                  ID = c(1621, 1621, 1628,1628,3101, 3101,3105,3105,1621, 1621, 1628,1628 ), 
                  category= c("0910","0910","0911","0913", "0914", "0910","0910","0911","1014","1012","1011","1013"),
                  var1 = c(60,70, 400,300,15,20, 200,150,61,71,401,301) )

df2是所需的结果(见var2):

> df2 = data.table( Year = c(2009,2009,2009,2009,2009,2009,2009,2009,2010,2010,2010,2010),
                  ID = c(1621, 1621, 1628,1628,3101, 3101,3105,3105,1621, 1621, 1628,1628 ), 
                  category= c("0910","0910","0911","0913", "0914", "0910","0910","0911","1014","1012","1011","1013"),
                  var1 = c(60,70, 400,300,15,20, 200,150,61,71,401,301), 
                  var2= c(130,130,700,700,35,35,350,350,132,132,702,702) )

所以我想计算按var1分组的IDcategory的前两个整数

的总和

因此,如果变量类别的前两个整数是09(或10等等),则按var2分组IDcategory的前两个整数}。然后,相同类别中的相等ID应分配相同的总和。

我试图通过

实现这一目标
> df1$var2 = rep(NA, rep(length(df1$ID)))
df1$var2 = ifelse(substr(df1$category,1,2)=="09", by(df1[Year==2009,]$var1, df1[Year==2009,]$ID,sum), df1$var2)
df1$Var2 = ifelse(substr(df1$category,1,2)=="10", by(df1[Year==2010,]$var1, df1[Year==2010,]$ID,sum), df1$var1)

但是这里的总和没有分配给正确的项目。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

df1 = data.frame( Year = c(2009,2009,2009,2009,2009,2009,2009,2009,2010,2010,2010,2010),
                  ID = c(1621, 1621, 1628,1628,3101, 3101,3105,3105,1621, 1621, 1628,1628 ), 
                  category= c("0910",NA,"0911","0913", "0914", "0910","0910",NA,"1014","1012",NA,"1013"),
                  var1 = c(60,70, 400,300,15,20, 200,150,61,71,401,301) )

我在OP的原始数据帧中添加了NA值,以反映他所需的完整规范。

df1$category_sub = substr(df1$category, 1, 2)
df1_aggre = aggregate(var1 ~ ID + category_sub, data = df1, sum)
names(df1_aggre)[3] = "var2"

df2 = merge(df1, df1_aggre, all=TRUE)
df2[order(df2$Year),]

结果:

> df2[order(df2$Year),]
     ID category_sub Year category var1 var2
1  1621           09 2009     0910   60   60
4  1621         <NA> 2009     <NA>   70   NA
5  1628           09 2009     0911  400  700
6  1628           09 2009     0913  300  700
9  3101           09 2009     0914   15   35
10 3101           09 2009     0910   20   35
11 3105           09 2009     0910  200  200
12 3105         <NA> 2009     <NA>  150   NA
2  1621           10 2010     1014   61  132
3  1621           10 2010     1012   71  132
7  1628           10 2010     1013  301  301
8  1628         <NA> 2010     <NA>  401   NA

我首先从category中提取前两个整数,然后按var1IDcategory_sub进行分组。然后,我将var1重命名为var2,并将df1df1_aggre合并为ID,将category_sub合并为all=TRUE选项。这指定了完整的外部联接。生成的数据框未排序,因此我将df2排序为Year以获得所需的结果。