How to calculate a monthly mean?
Asked Answered
P

1

0

I have the daily weather report like this. What I want is to calculate the monthly mean of the max, min and observation temperature and then plot these three lines. I already convert the date format like this:

Date = as.POSIXlt(Weather2011$Date, format = "%m/%d/%Y")  
Year = as.numeric(format(Date, format = "%Y"))
Month = as.numeric(format(Date, format = "%m"))
Week = as.numeric(format(Date, format = "%U"))
Weekday = as.numeric(format(Date, format = "%w"))

Weather2011 looks like this:

Date      Max.Temp  Min.Temp  Temp  Date        Year   Month  Week  Weekday
6/3/2010  87        63        63    2010-06-03  2010   6      22    4
6/4/2010  83        63        73    2010-06-04  2010   6      22    5
Prajna answered 8/5, 2012 at 17:52 Comment(3)
Can you provide a small reproducible example data set?Dortheydorthy
You seem to have removed the link to the picture of your example data and instead posted a poorly formatted version of the first line. You also removed your actual question completely. Please update your question if you want to receive a decent answer.Dortheydorthy
Thanks man, this is my first question here,sorry about that.Prajna
H
3

I find that tapply works well. Ex.

x <- seq(from=as.Date("2000-01-01"), to=as.Date("2004-12-31"), by="day")
y <- sin(seq(from=0, to=2*pi*5,length.out=length(x)))+rnorm(length(x))
yyyymm <- paste(format(as.POSIXlt(x), format="%Y-%m"), "01", sep="-")
MEAN <- tapply(y, yyyymm, mean)
MAX <- tapply(y, yyyymm, max)
MIN <- tapply(y, yyyymm, min)
#plots
x11()
par(mfcol=c(1,2))
plot(x,y, ylim=range(MEAN, MAX, MIN), ylab="", xlab="")
plot(as.POSIXlt(names(MEAN)), MEAN, t="l", ylim=range(MEAN, MAX, MIN), ylab="", xlab="")
lines(as.POSIXlt(names(MEAN)), MAX, lty=2)
lines(as.POSIXlt(names(MEAN)), MIN, lty=2)

enter image description here

Hod answered 8/5, 2012 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.