Calculation of average values ​​in tables using formulas [R]

I know that commands like xtabs and table allow the user to do cross tabs

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 expand the formula so that it can show the sum of horse power for cars in each bunker

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

Now I wonder, is it possible to calculate the average horsepower for cars in each bunker? e.g. something like this xtabs(mean(hp)~cyl+gear, data = mtcars)

+6
source share
4 answers

You can do this in one line using cast from reshape library

 cast(mtcars, cyl ~ gear, value = 'hp', fun = mean) 
+10
source

One interesting answer I received from r-help is as follows:

 > 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 > 
+7
source

(Moving my comment to the answer, so I can better edit it.)

I'm not sure how to do this using xtabs (which I have never used before), but here are a few ways to do this using the reshape and plyr .

 > x = melt(mtcars, id = c("cyl", "gear"), measure = c("hp")) > cast(x, cyl ~ gear, mean) > x = ddply(mtcars, .(cyl, gear), summarise, hp = mean(hp)) > cast(x, cyl ~ gear) 
+3
source

Another way to calculate is to use the aggregate () function. Although the output is not in the form of a table. (via twitter )

 > aggregate(hp~cyl+gear,data=mtcars,mean) cyl gear hp 1 4 3 97.0000 2 6 3 107.5000 3 8 3 194.1667 4 4 4 76.0000 5 6 4 116.5000 6 4 5 102.0000 7 6 5 175.0000 8 8 5 299.5000 > 
0
source

Source: https://habr.com/ru/post/893392/


All Articles