2013-02-16 65 views
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 

谢谢。

+0

downvote不从我,但请[阅读](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)和编辑您的帖子,因为它现在可能会被关闭。 – 2013-02-16 19:16:19

+0

@ user1317221_G,它看起来更好,如果这就是你的意思。 – 700resu 2013-02-16 19:28:00

+4

这个问题的答案几乎在我见过的每个R-tutorial中。花点时间完成其中的一个,你会为自己节省大量的时间。 – N8TRO 2013-02-16 19:47:05

回答

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) 
+0

谢谢。但我有个问题。我尝试现在整理并使用** newdf <-newdf [order(Income),] **但它似乎不起作用。它说没有找到对象“收入”。 newdf有不同的结构吗?我也尝试改变** newdf <-newdf [,order(Income)] **。 – 700resu 2013-02-16 20:29:57

+0

我想你可能想要做这样的事情: 'newdf [with(newdf,order(Income)),]'check [this post](http://stackoverflow.com/a/1296745/1317221)在你的答案中增加了一个额外的'ddply'代码行,以帮助你得到一个名为'Income'的平均列的'newdf' – 2013-02-16 20:48:59