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
8 12 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
8 2330 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)
You can do it in one line using cast
from the reshape
library
cast(mtcars, cyl ~ gear, value = 'hp', fun = mean)
One interesting response that I received from r-help is as following:
> attach(mtcars)
> tapply(hp,list(cyl,gear),mean)
3 4 5
4 97.0000 76.0 102.0
6 107.5000 116.5 175.0
8 194.1667 NA 299.5
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With