各位好,小弟如下的问题,在一个非平衡面板数据当中,每一个id的拥有的观测值不同,这样的话如何根据id实现个体观测值的乘法运算?

首先,在平衡面板当中,因为每个id拥有的观测期一样,假定是四期,在如下的数据当中:

# balanced data
library(matrixStats)
df <- data.frame(ID = rep(c(1,2,3),4),
                 Chinese = c(1,2,3,4,5,6,7,8,9,11,12),
                 Math = c(1,2,3,4,5,6,7,8,9,11,12),
                 English = c(1,2,3,4,5,6,7,8,9,11,12)
)
df <- arrange(df,ID)
#数据如下
ID Chinese Math English
1   1       1    1       1
2   1       4    4       4
3   1       7    7       7
4   1      10   10      10
5   2       2    2       2
6   2       5    5       5
7   2       8    8       8
8   2      11   11      11
9   3       3    3       3
10  3       6    6       6
11  3       9    9       9
12  3      12   12      12
#计算语数英三门课的总分
df$total <- df$Chinese + df$Math + df$English
#计算每个人每次总分之积
y <- unlist(df["total"]) 
mpri <- rowProds(matrix(y, ncol = 4, byrow = TRUE))

如上,对于平衡面板来说,计算每次总分之和可以通过rowProds迅速实现;但是在非平衡面板当中,每个id的次数都不一样:

library(matrixStats)    
df <- data.frame(ID = rep(c(1,2,3),c(1,2,3)),
                 Chinese = c(1,2,3,4,5,6,7,8,9,11,12,13),
                 Math = c(1,2,3,4,5,6,7,8,9,11,12,13),
                 English = c(1,2,3,4,5,6,7,8,9,11,12,13)
)
df <- arrange(df,ID)              
df$total <- df$Chinese + df$Math + df$English
#数据如下
   ID Chinese Math English total
1   1       1    1       1     3
2   1       7    7       7    21
3   2       2    2       2     6
4   2       3    3       3     9
5   2       8    8       8    24
6   2       9    9       9    27
7   3       4    4       4    12
8   3       5    5       5    15
9   3       6    6       6    18
10  3      11   11      11    33
11  3      12   12      12    36
12  3      13   13      13    39

这样,1号有2期的总分,2号有4期的总分,3号有6期的总分,这种情况下请问这么将每个id在每期的总分按照id来进行乘法运算,并且结果同前述平衡面板下使用rowProds的结果一样仍然是个行矩阵。
敬请指导