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