Skip to content
Prev 29892 / 63462 Next

calculating means per group

Hi Luc,

First of all, questions like this should really be asked on the R-help  
mailing list.

The tapply function does what you want:

 > year
  [1] 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2
Levels: 1 2
 > area
  [1] a a a a a b b b b a a a a b b b b b
Levels: a b
 > value
  [1] 20 25 28 31 23 25 28 23 19 25 23 24 26 27 28 20 25 28

Note that both year and area are factors.

Get the mean for each area:

 > tapply(value, area, mean)
        a        b
25.00000 24.77778

If you make the second argument a list then you can subset on both  
factor columns:

 > tapply(value, list(year, area), mean)
      a     b
1 25.4 23.75
2 24.5 25.60

Kjell
On 4 sept. 08, at 09:06, RFTW wrote: