3

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

Community
  • 1
  • 1
emanuele
  • 2,519
  • 8
  • 38
  • 56

2 Answers2

8

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.

agstudy
  • 119,832
  • 17
  • 199
  • 261
8

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)
Braiam
  • 1
  • 11
  • 47
  • 78
Jean V. Adams
  • 4,634
  • 2
  • 29
  • 46