2013-02-16 68 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