r - Aggregate / summarize multiple variables per group (i.e. sum, mean, etc) -
from data frame, there easy way aggregate (i.e. sum) multiple variables simultaneously?
below sample data:
library(lubridate) days = 365*2 date = seq(as.date("2000-01-01"), length = days, = "day") year = year(date) month = month(date) x1 = cumsum(rnorm(days, 0.05)) x2 = cumsum(rnorm(days, 0.05)) df1 = data.frame(date, year, month, x1, x2) i simultaneously aggregate x1 , x2 variables df2 data frame year , month. following code aggregates x1 variable, possible simultaneously aggregate x2 variable?
### aggregate variables year month df2=aggregate(x1 ~ year+month, data=df1, sum, na.rm=true) head(df2) any suggestions appreciated.
where year() function from?
you use reshape2 package task:
require(reshape2) df_melt <- melt(df1, id = c("date", "year", "month")) dcast(df_melt, year + month ~ variable, sum) # year month x1 x2 1 2000 1 -80.83405 -224.9540159 2 2000 2 -223.76331 -288.2418017 3 2000 3 -188.83930 -481.5601913 4 2000 4 -197.47797 -473.7137420 5 2000 5 -259.07928 -372.4563522
Comments
Post a Comment