Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

dataframe - calculate average of each column based on values in another column in R

with the built-in dataframe mtcars, let's say I want to calculate the average each column based on the values in column 'carb'. How do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for the aggregate function. It is nicely explained in this previous post.

For mtcars this would look like this for all other columns:

aggregate(. ~ carb, mtcars, mean)
  carb      mpg      cyl     disp    hp     drat     wt     qsec  vs        am     gear
1    1 25.34286 4.571429 134.2714  86.0 3.681429 2.4900 19.50714 1.0 0.5714286 3.571429
2    2 22.40000 5.600000 208.1600 117.2 3.699000 2.8628 18.18600 0.5 0.4000000 3.800000
3    3 16.30000 8.000000 275.8000 180.0 3.070000 3.8600 17.66667 0.0 0.0000000 3.000000
4    4 15.79000 7.200000 308.8200 187.0 3.596000 3.8974 16.96500 0.2 0.3000000 3.600000
5    6 19.70000 6.000000 145.0000 175.0 3.620000 2.7700 15.50000 0.0 1.0000000 5.000000
6    8 15.00000 8.000000 301.0000 335.0 3.540000 3.5700 14.60000 0.0 1.0000000 5.000000

Or like this for only once specific column (e. g. mpg):

> aggregate(mpg ~ carb, mtcars, mean)
carb      mpg
1    1 25.34286
2    2 22.40000
3    3 16.30000
4    4 15.79000
5    6 19.70000
6    8 15.00000

Edit: Had sum mixed up with mean, sorry. Corrected it to mean.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...