[R] How can I calculate conditional mean in a large dataset including date data

Gabor Grothendieck ggrothendieck at gmail.com
Thu Feb 1 15:43:29 CET 2007


You could also use aggregate with the zoo package.  Using the same
input data that Vladimir used, create a zoo variable and aggregate it:

> library(zoo)
> z <- zoo(dfr[,2], as.Date(dfr[,1], "%d/%m/%Y"))
> aggregate(z, as.yearmon, mean)
Jan 1970 Dec 2003
    0.00     1.25

zoo is described in the vignette:

library(zoo)
vignette("zoo")


On 2/1/07, Vladimir Eremeev <wl2776 at gmail.com> wrote:
>
> >
> dfr<-data.frame(day=c("1/1/1970","5/1/1970","5/12/2003","31/12/2003"),temperature=c(1,-1,2,0.5))
> > dfr
>        day temperature
> 1   1/1/1970         1.0
> 2   5/1/1970        -1.0
> 3  5/12/2003         2.0
> 4 31/12/2003         0.5
>
> > aggregate(dfr["temperature"],by=list(format(as.Date(dfr$day,format="%d/%m/%Y"),"%m-%Y")),mean,na.rm=TRUE)
>  Group.1 temperature
> 1 01-1970        0.00
> 2 12-2003        1.25
>
> > aggregate(dfr["temperature"],by=list(format(as.Date(dfr$Dt,format="%d/%m/%Y"),"%m")),mean,na.rm=TRUE)
>  Group.1 temperature
> 1      01        0.00
> 2      12        1.25
>
>
> Majid Iravani wrote:
> >
> > Dear R users,
> >
> > I have a dataframe with two columns: first column is date data (e.g.
> > 1/1/2000 with character format: daily data from 1/1/1970 till 31/12/2003)
> > and second column is temperature value. Now I'd like to calculate mean for
> > each month in a year (i.e. May 2001, June 1997) and mean for each month in
> > all of years. As the number of days in some months is different from
> > others
> > I could not write appreciate command for this. Therefore I would greatly
> > appreciate if somebody can help me in this case
> >
> > Thank you
> > Majid
> >
> >
>
> --
> View this message in context: http://www.nabble.com/-R--How-can-I-calculate-conditional-mean-in-a-large-dataset-including-date-data-tf3154751.html#a8748821
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list