2
如何在R中的范围上投射聚合值并用零填充缺失的范围值。如何在R中的范围上投射聚合值并用零填充缺失的范围值
df <- data.frame (year = sample(c(2014:2016), 100, replace=T),
month = sample(c(1:5,8:12), 100, replace=T),
int = 1)
# install.packages("reshape")
library(reshape)
month <- cast(df, year ~ month, sum, value = 'int')
month
输出:
# output
year 1 2 3 4 5 8 9 10 11 12
1 2014 6 5 4 3 4 4 3 3 9 2
2 2015 4 9 1 3 1 4 3 3 2 3
3 2016 0 3 3 4 4 1 4 1 3 1
如何设置缺少个月零?结果应该是这样的:
# output
year 1 2 3 4 5 >6< >7< 8 9 10 11 12
1 2014 6 5 4 3 4 0 0 4 3 3 9 2
2 2015 4 9 1 3 1 0 0 4 3 3 2 3
3 2016 0 3 3 4 4 0 0 1 4 1 3 1
有没有办法通过强制转换功能来做到这一点?
尼斯的答案!我更喜欢**'xtabs' **,因为它不需要任何附加软件包! – wittich
对于**'xtabs' **,它有助于在输出中使用**'as.data.frame.matrix()**。 – wittich