[R] how to calculate "conditional" mean?

Gabor Grothendieck ggrothendieck at myway.com
Sun Dec 5 17:26:11 CET 2004


Terry Mu <muster <at> gmail.com> writes:

: 
: a data set like this:
: 
: year   month    day    count
: 2001     1            1         10
: 2001     1            2          11
: ....
: 2004     7            17        8
: ....
: 
: basically it is a count of of some numbers everyday through a few years
: 
: now I'd like to get the mean of the count for every day. 
: 
: I thought I can do this using for and ifelse,
: but is there a simple way to do this? I wish a function like 
: mean(count, 'only when year, month, day are equal') could do this.

You want to represent your dates as objects of the Date class
and then use tapply.  (See ?as.Date, ?Date, ?tapply, ?paste, ?with. 
Also look up ?aggregate and ?by and read about dates in R News 4/1.)  
Assuming DF is your data frame:

    Dates <- with(DF,  
        as.Date( paste(year, month, day, sep="-") )  
    )
    tapply(DF$count, Dates, mean)




More information about the R-help mailing list