How to cast aggregated values over a range in R and fill missing range values with zero.
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:
# 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
How do I set the missing months to zero? The result should be like that:
# 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
Is there a way to do it over the cast function?