简体   繁体   中英

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM