0

我有一份样本调查表;人口统计之类的东西。其中一列是country (factor)另一列annual income。现在,我需要计算每个国家的平均值并存储在新data.framecountry和相应的平均值中。它应该很简单,但我迷路了。数据类似于下图所示:

Country  Income($) Education ... ... ...
1. USA    90000      Phd
2. UK     94000      Undergrad
3. USA    94000      Highschool
4. UK     87000      Phd
5. Russia 77000      Undergrad
6. Norway 60000      Masters
7. Korea  90000      Phd
8. USA    110000     Masters
.
.

我需要一个最终结果,例如:

USA   UK    Russia ...
98000 90000 75000

谢谢你。

4

1 回答 1

5

数据示例:

dat <- read.table(text="Country  Income Education 
 USA    90000      Phd
 UK     94000      Undergrad
 USA    94000      Highschool
 UK     87000      Phd
 Russia 77000      Undergrad
 Norway 60000      Masters
 Korea  90000      Phd
 USA    110000     Masters",header=TRUE)

做你想做的事plyr

如果您的数据被调用dat

library(plyr)
newdf <- ddply(dat, .(Country), function(x) Countrymean = mean(x$Income))

# newdf <- ddply(dat, .(Country), function(x) data.frame(Income = mean(x$Income)))

和聚合:

 newdf <- aggregate(Income ~ Country, data = dat, FUN = mean)

对于您最后显示的输出可能tapply吗?

tapply(dat$Income, dat$Country, mean)
于 2013-02-16T19:33:06.000 回答