Compute data.frame column averages by date

送分小仙女□ 提交于 2019-12-04 10:59:16
library(plyr)

ddply(df, .(Date), summarize, daily_mean_Temp = mean(Temp))

This is a simple example of the Split-Apply-Combine paradigm.

Alternative #1 as Ananda Mahto mentions, dplyr package is a higher-performance rewrite of plyr. He shows the syntax.

Alternative #2: aggregate() is also functionally equivalent, just has fewer bells-and-whistles than plyr/dplyr.


Additionally 'generate average for every 7 calendar days': do you mean 'average-by-week-of-year', or 'moving 7-day average (trailing/leading/centered)'?

Here are a few options:

aggregate(Temp ~ Date, mydf, mean)
#     Date     Temp
# 1 1/2/13 35.03333
# 2 1/4/13 39.55000
# 3 1/5/13 45.20000

library(dplyr)
mydf %.% group_by(Date) %.% summarise(mean(Temp))
# Source: local data frame [3 x 2]
# 
#     Date mean(Temp)
# 1 1/2/13   35.03333
# 2 1/4/13   39.55000
# 3 1/5/13   45.20000

library(data.table)
DT <- data.table(mydf)
DT[, mean(Temp), by = Date]
#      Date       V1
# 1: 1/2/13 35.03333
# 2: 1/4/13 39.55000
# 3: 1/5/13 45.20000

library(xts)
dfX <- xts(mydf$Temp, as.Date(mydf$Date))
apply.daily(dfX, mean)
#             [,1]
# 1-02-13 35.03333
# 1-04-13 39.55000
# 1-05-13 45.20000

Since you are dealing with dates, you should explore the xts package, which will give you access to functions like apply.daily, apply.weekly, apply.monthly and so on which will let you conveniently aggregate your data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!