Skip to content

How to monthly,daily,yearly average

3 messages · Qianfeng Li, Tammy Ma, Gabor Grothendieck

#
Here is an example.  See the three vignettes in zoo:
vignette("zoo")
and R News 4/1 for info on dates.

# assume this input

Lines <- "Date Time Value
01/01/08 00:00:00 1
01/01/08 00:30:00 2
01/01/08 01:00:00 3
01/01/08 01:30:00 4
01/01/08 02:00:00 5
01/01/08 02:30:00 6
01/01/08 03:00:00 7
01/01/08 03:30:00 8
01/01/08 04:00:00 9"

# read in the data, convert it to zoo, aggregate it and plot

library(zoo)
library(chron)

# DF <- read.table("myfile.dat", header = TRUE, as.is = TRUE)
DF <- read.table(textConnection(Lines), header = TRUE, as.is = TRUE)

# next line may need to specify formats, if different
z <- zoo(DF$Value, chron(DF$Date, DF$Time))

# hourly aggregation
z.hr <- aggregate(z, trunc(time(z), "01:00:00"), mean)
plot(z.hr, type = "o")

# daily aggregation
z.day <- aggregate(z, trunc, mean)
plot(z.day, type = "o")

# monthly aggregation
z.mo <- aggregate(z, as.yearmon, mean)
plot(z.mo, type = "o")

# yearly aggregation
z.yr <- aggregate(z.mo, floor, mean)
plot(z.yr, type = "o")
On Wed, Mar 11, 2009 at 9:25 AM, Qianfeng Li <qflichem at yahoo.com> wrote: