2010-05-12 61 views
9
a.2<-sample(1:10,100,replace=T) 
b.2<-sample(1:100,100,replace=T) 
a.3<-data.frame(a.2,b.2) 

r<-sapply(split(a.3,a.2),function(x) which.max(x$b.2)) 

a.3[r,] 

返回列表索引,而不是整個data.frame指數在R A組中選擇具有可變的最大值的行

我試着去爲a.2每個子組返回b.2最大價值。我怎樣纔能有效地做到這一點?

+0

熔體(A.3,ID = C ( 「A.2」)) - > H.2; cast(h.2,a.2〜,max) 在這個例子中做了竅門,但是當我將計算機應用到我的原始數據集時,計算機的內存不足。所以沒有真正幫助我很多。 – Misha 2010-05-12 20:15:58

回答

6
a.2<-sample(1:10,100,replace=T) 
b.2<-sample(1:100,100,replace=T) 
a.3<-data.frame(a.2,b.2) 

由喬納森·常答案讓你你明確地要求,但我猜你想從數據幀中的實際行。

sel <- ave(b.2, a.2, FUN = max) == b.2 
a.3[sel,] 
+0

這很簡單,我必須承認..但是== b.2後面的邏輯超出了我的範圍...... – Misha 2010-05-12 23:59:51

+0

ave生成的矢量只包含每個a.2的最大值b.2。因此,只要數據幀有行,它就會在其中設置真值。您正在使用邏輯向量來選擇數據框中的行。如果你想看看它是如何工作的,將ave命令的結果添加到你的數據框中,然後查看它,與b.2列比較 - a.3 $ b.max < - ave(b.2,a。 2,FUN = max) 。此外,您可以使用sel變量並在上下文中查看它 - a.3 $ sel < - a.3 $ b.2 == a.3 $ b.max – John 2010-05-13 02:05:06

+0

Thx ...我感謝您的努力。 – Misha 2010-05-13 07:57:12

1
a.2<-sample(1:10,100,replace=T) 
b.2<-sample(1:100,100,replace=T) 
a.3<-data.frame(a.2,b.2) 
m<-split(a.3,a.2) 
u<-function(x){ 
    a<-rownames(x) 
    b<-which.max(x[,2]) 
    as.numeric(a[b]) 
    } 
r<-sapply(m,FUN=function(x) u(x)) 

a.3[r,] 

這雖然有點麻煩,但它有點麻煩......但它允許我抓住組的最大值的行。任何其他想法?

1
> a.2<-sample(1:10,100,replace=T) 
> b.2<-sample(1:100,100,replace=T) 
> tapply(b.2, a.2, max) 
1 2 3 4 5 6 7 8 9 10 
99 92 96 97 98 99 94 98 98 96 
8
library(plyr) 
ddply(a.3, "a.2", subset, b.2 == max(b.2)) 
+0

我嘗試過使用ddply函數,但它非常緩慢。我沒有時間它,但它持續了一個咖啡杯和一趟衛生間,而我的原始數據集(210col * 16000rows)中僅使用了0.2s。 – Misha 2010-05-13 22:52:09

+1

這將在下一個版本中修復。但是除非你提供一個現實的例子,否則你不可能期望得到能夠處理你的數據的答案! – hadley 2010-05-14 03:04:21

10

ddplyave方法都是相當耗費資源,我想。 ave由於我目前的問題(67,608行,有四列定義唯一鍵)而用完內存而失敗。 tapply是一個方便的選擇,但我通常需要做的是爲每個唯一鍵(通常由多個列定義)選擇具有something-est some-value的所有行。我找到的最佳解決方案是進行排序,然後使用duplicated的否定來爲每個唯一鍵只選擇第一行。對於簡單的例子在這裏:

a <- sample(1:10,100,replace=T) 
b <- sample(1:100,100,replace=T) 
f <- data.frame(a, b) 

sorted <- f[order(f$a, -f$b),] 
highs <- sorted[!duplicated(sorted$a),] 

我認爲隨着aveddply的性能提升,至少,是巨大的。對於多列鍵來說它稍微複雜一點,但order將處理大量的事情,duplicated可以處理數據幀,所以可以繼續使用這種方法。

+0

這是最容易使用的,並且在多列上運行良好 - 您只需在'duplicateated'中使用'cbind'。 – 2013-04-07 09:28:47

0
a.2<-sample(1:10,100,replace=T) 
b.2<-sample(1:100,100,replace=T) 
a.3<-data.frame(a.2,b.2) 

aggregate有了,就可以得到各組的最大在一行:

aggregate(a.3, by = list(a.3$a.2), FUN = max) 

這將產生以下輸出:

Group.1 a.2 b.2 
1  1 1 96 
2  2 2 82 
... 
8  8 8 85 
9  9 9 93 
10  10 10 97 
相關問題