emanuele
emanuele

Reputation: 2589

Aggregate data by week, month etc in R

I need to aggregate my data Kg

            Data  Kg
    1 2013-03-01 271
    2 2013-03-06 374
    3 2013-03-07  51
    4 2013-03-12 210
    5 2013-03-13 698
    6 2013-03-15 328

by week or month. I have found this answer here in stackoverflow, but I really don't understand the answer. Who can show me how can I do this case. Thanx

Upvotes: 3

Views: 13725

Answers (2)

Jean V. Adams
Jean V. Adams

Reputation: 4784

Or, you could use tapply to apply by group of weeks. Here I am using lubridate package to extract week part from a date.

# fake data
df <- structure(list(Datechar = c("2013-03-01", "2013-03-06", "2013-03-07", 
    "2013-03-12", "2013-03-13", "2013-03-15"), Kg = c(271L, 374L, 
    51L, 210L, 698L, 328L)), .Names = c("Datechar", "Kg"), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6"))
# convert character to date
df$Date <- as.Date(df$Datechar)

# calculate mean kg for each week
library(lubridate)
tapply(df$Kg, week(df$Date), mean)
tapply(df$Kg, month(df$Date), mean)

Upvotes: 8

agstudy
agstudy

Reputation: 121568

The answer mentioned suggest that you should to use xts package.

library(xts)
## create you zoo objects using your data
## you replace text argument by read.zoo(yourfile, header = TRUE)
x.zoo <- read.zoo(text='  Data  Kg         
+     1 2013-03-01 271
+     2 2013-03-06 374
+     3 2013-03-07  51
+     4 2013-03-12 210
+     5 2013-03-13 698
+     6 2013-03-15 328',header=TRUE)
### then aggregate
apply.weekly(x.zoo, mean)   ## per week
apply.monthly(x.zoo, mean)   ## per month

see ??apply.xxxly:

Essentially a wrapper to the xts functions endpoints and period.apply, mainly as a convenience.

Upvotes: 8

Related Questions