How can I get xtabs to calculate means instead of sums in R?

Waldir Leoncio picture Waldir Leoncio · Jan 25, 2012 · Viewed 8.4k times · Source

I have a data frame where each line represents an individual. That data frame has two variables: age and year. I want to make a table of average ages per year. How can I do it?

The best I could come up with was xtabs(age ~ year, dataframe), but this gives me the sum of ages per year.

Answer

James picture James · Jan 25, 2012

Use aggregate:

xtabs(hp~cyl+gear,aggregate(hp~cyl+gear,mtcars,mean))
   gear
cyl        3        4        5
  4  97.0000  76.0000 102.0000
  6 107.5000 116.5000 175.0000
  8 194.1667   0.0000 299.5000