[R] Calculating mean together with split

hadley wickham h.wickham at gmail.com
Wed Sep 20 17:39:28 CEST 2006


> It contains about 19000 entries and the structure looks like this:
>
>   NoPlants                  sim run year DensPlants
> 1        6 lng_cs99_renosterbos   1    4    0.00192
> .
> .
> .
>
> it has 43 different entries for sim and year goes from 1 to 100, and run
> from 1 to 5.
>
> I would like to calculate the mean of DensPlants for each simulation and
> each year seperately, i.e. calculating the mean for all combinations of
> sim and year over run.

You can do this pretty easily with the reshape package:

library(reshape)
dfm <- rename(df, c(DensPlants = value)) # this is the form that reshape wants

# Then try one of these:

cast(dfm, year ~ sim)
cast(dfm, year + sim ~ . )
cast(dfm, year ~ sim, margins=TRUE)

Depending on what format you want the resulting summaries in.

Hadley



More information about the R-help mailing list