R: Summarize Data by Month and Year (Similar to pivot table) -
i trying summarize data in r month , year. using ddply function summarize data want change , doing normal transpose doesn't give me desired results. loading csv file daily river bypass data. data has following fields: date, year, month, day , bypass. use following code summarize file:
summary<- ddply(file,c("year", "month"), summarise, sum = round(sum(bypass*1.9835),0)) summary
the output looks like:
year month sum 1946 10 1791 1946 11 1575 1946 12 1129 1947 1 823 1947 2 750 1947 3 1023
(and goes on ~61 years of data)
so question... there way transform data output in following way:
month year 1 2 3 4 5 6 7 8 9 10 11 12 1946 1791 1575 1129 1947 823 750 1023
i copied in sample of data goes through 2007.
thanks in advance
library(reshape2) dcast(df, iyear ~ month, value.var='sum')
output:
iyear 1 2 3 10 11 12 1 1946 na na na 1791 1575 1129 2 1947 823 750 1023 na na na
if want replace nas zeros:
df1 <- dcast(df, iyear ~ month, value.var='sum') df1[is.na(df1)] <- 0 iyear 1 2 3 10 11 12 1 1946 0 0 0 1791 1575 1129 2 1947 823 750 1023 0 0 0
data:
df <- structure(list(iyear = c(1946l, 1946l, 1946l, 1947l, 1947l, 1947l ), month = c(10l, 11l, 12l, 1l, 2l, 3l), sum = c(1791l, 1575l, 1129l, 823l, 750l, 1023l)), .names = c("iyear", "month", "sum" ), class = "data.frame", row.names = c(na, -6l)) iyear month sum 1 1946 10 1791 2 1946 11 1575 3 1946 12 1129 4 1947 1 823 5 1947 2 750 6 1947 3 1023
Comments
Post a Comment