[R] Calculating the mean of values in tables using formulae

Mark Alen linux_jvm at yahoo.com
Sat Jul 23 07:02:10 CEST 2011


I know commands like xtabs and table allow a user to do cross-tabulation
For example the following command generates a pivot table that shows the number of cars that have the same number of gears and cylinders.

>xtabs(~cyl+gear,data =mtcars)
   gear
cyl  3 4 5
  4 1 8 2
  6 2 4 1
  812 0 2
>

We can extend the formula so it could show the sum of the horse power for the cars in each bin

>xtabs(hp~cyl+gear,data =mtcars)
   gear
cyl    3   4   5
  4  97 608 204
  6 215 466 175
  82330   0 599
>

I am now wondering, is it possible to calculate the mean of horse powers for cars in each bin? for example something like this xtabs(mean(hp)~cyl+gear, data = mtcars)

Thank you 
Mark




More information about the R-help mailing list