如何获得xtabs来计算均值而不是R中的总和? [英] How can I get xtabs to calculate means instead of sums in R?

查看:102
本文介绍了如何获得xtabs来计算均值而不是R中的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中每一行代表一个人.该数据框具有两个变量:年龄和年份.我想做一张每年的平均年龄表.我该怎么办?

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?

我能想到的最好的方法是xtabs(age ~ year, dataframe),但这给了我每年的年龄总和.

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

推荐答案

使用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

这篇关于如何获得xtabs来计算均值而不是R中的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆