# [R] Newbie: how to calculate group averagege?

Kaspar Pflugshaupt pflugshaupt at geobot.umnw.ethz.ch
Mon Apr 10 14:07:16 CEST 2000

```(message from 10.4.2000 12:58 Uhr):

> Dear R-List,
>
> I´m new in R, so I hope my question is not to primitive, but I haven´t
> found a solution in the R-help. I´ve got a datatframe with 3 factors,
> called xf (9 levels), yf (9 levels), zf (3 levels) and one variable
> (rt):
>

Hello Sven,

try "tapply". From its help page:

> Apply a Function Over a ``Ragged'' Array
>
>
> Usage
>
> tapply(X, INDEX, FUN = NULL, simplify = TRUE, ...)
>
> Arguments
>
> X
> an atomic object, typically a vector.
> INDEX
> list of factors, each of same length as X.
> FUN
> the function to be applied. In the case of functions like +, %*%, etc., the
> function name must be quoted. If FUN is NULL, tapply returns a vector which
> can be used to subscript the multi-way array tapply normally produces.
> simplify
> If FALSE, tapply always returns an array of mode "list". If TRUE (the
> default), then if FUN always returns a scalar, tapply returns an array with
> the mode of the scalar.
> ...
> optional arguments to FUN.

So, just give it a list of your grouping factors as second argument and
"mean" as function, and you're set. If you still get many NAs, you might
consider giving na.rm=T as additional argument, thus writing

tapply(data, list(factor1,factor2 ...), FUN=mean, na.rm=T)

The last argument is passed on to the mean function.

Hope it works for you

Kaspar

--

Kaspar Pflugshaupt
Geobotanisches Institut
Zuerichbergstr. 38
CH-8044 Zuerich

Tel. ++41 1 632 43 19
Fax  ++41 1 632 12 15

mailto:pflugshaupt at geobot.umnw.ethz.ch
privat:pflugshaupt at mails.ch
http://www.geobot.umnw.ethz.ch

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```