2012-08-30 49 views
-5

可能重複:
Idiomatic R code for partitioning a vector by an index and performing an operation on that partition
How to calculate median of profits for a particular country如何通過COL2找到COL1分組的平均

我試圖通過使用R.另一列找到一列的平均在SQL中執行它非常容易,但無法找到正確的函數並實現它們。下面是一些示例數據。

data("Forbes2000", package = "HSAUR") 
head(Forbes2000) 

## rank    name  country    category sales profits assets marketvalue 
## 1 1   Citigroup United States    Banking 94.71 17.85 1264.03  255.30 
## 2 2 General Electric United States  Conglomerates 134.19 15.59 626.93  328.54 
## 3 3 American Intl Group United States   Insurance 76.66 6.46 647.66  194.87 
## 4 4   ExxonMobil United States Oil & gas operations 222.88 20.96 166.99  277.02 
## 5 5     BP United Kingdom Oil & gas operations 232.57 10.27 177.57  173.54 
## 6 6  Bank of America United States    Banking 49.01 10.81 736.45  117.55 
+2

有很多方法可以做到這一點。查看'plyr','data.table','sqldf'軟件包(提到幾個),並在基礎R中使用函數'aggregate','tapply'和'ave'。 SO有很多相關的問題。 – mnel

+2

你應該再試一次,這個問題已經在SO上回答過100次了。查看'plyr','data.table'標籤以及'ddply'函數,特別是''aggregate'',''ave'或者其他任意數量的函數。 [這個問題](http://stackoverflow.com/questions/10748253/idiomatic-r-code-for-partitioning-a-vector-by-an-index-and-performing-an-operati/10748470#10748470O)規定大部分選項的相當廣泛的列表以及每個選項的相對時間。 – Chase

+1

這個問題的一部分負面影響可能是由於不可能用R中通常的讀取。*函數導入該文件。您可以使用utils包中的'read.fwf'來完成,但這很痛苦。學習發佈應用於數據框頭部的'dput()'的輸出。 –

回答

2

隨着一個名爲dat data.frame看起來像:

 rank    name country  category sales profits assets marketvalue 
21  21 DaimlerChrysler Germany Consumer_dur 157.13 5.12 195.58  47.43 

嘗試(未經測試d /噸衆多的空間在文本函數read.table防止作出它的意義):

aggregate(dat[ , c("sales", "profits", "assets", "marketvalue")], # cols to aggregate 
      dat["country"],           # group column 
      FUN=mean)       # aggregation function