Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

r - How to convert by the minute data to hourly average data

I have one week of data with a reading every 5 seconds. An example of data is below.

9/1/2012 00:00:00    1
9/1/2012 00:00:05    2
9/1/2012 00:00:10    3

I want to calculate the hourly average for each day. Then make a multi-line plot of "average hourly reading vs. hour" with lines representing different dates.

The one I have here is for weekly average

data$date = as.POSIXct(strptime(data$date, 
                  format = "%d/%m/%Y %H:%M","GMT")) 
means <- aggregate(data["nox"], format(data["date"],"%Y-%U"),
                 mean, na.rm = TRUE) 

For daily average, it is

data$date = as.POSIXct(strptime(data$date, 
                 format = "%d/%m/%Y %H:%M","GMT"))
means <- aggregate(data["nox"], format(data["date"],"%Y-%j"),
                 mean, na.rm = TRUE) 

Any one knows how to calculate the hourly average for each day.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I like @DWin's answer, but I had also remembered seeing once a help file for ?cut.Date which can also be used in this case. I've made up some data so you can see the results over a few hours:

set.seed(1)
data <- data.frame(date = seq(from = ISOdatetime(2012, 01, 01, 00, 00, 00),
                              length.out = 4320, by=5),
                   nox = sample(1:20, 4320, replace=TRUE))

hr.means <- aggregate(data["nox"], 
                      list(hour = cut(data$date, breaks="hour")), 
                      mean, na.rm = TRUE)
hr.means
#                  hour      nox
# 1 2012-01-01 00:00:00 10.60694
# 2 2012-01-01 01:00:00 10.13194
# 3 2012-01-01 02:00:00 10.33333
# 4 2012-01-01 03:00:00 10.38194
# 5 2012-01-01 04:00:00 10.51111
# 6 2012-01-01 05:00:00 10.26944

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...