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
最大價值。我怎樣纔能有效地做到這一點?
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
最大價值。我怎樣纔能有效地做到這一點?
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,]
這很簡單,我必須承認..但是== b.2後面的邏輯超出了我的範圍...... – Misha 2010-05-12 23:59:51
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
Thx ...我感謝您的努力。 – Misha 2010-05-13 07:57:12
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,]
這雖然有點麻煩,但它有點麻煩......但它允許我抓住組的最大值的行。任何其他想法?
> 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
的ddply
和ave
方法都是相當耗費資源,我想。 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),]
我認爲隨着ave
或ddply
的性能提升,至少,是巨大的。對於多列鍵來說它稍微複雜一點,但order
將處理大量的事情,duplicated
可以處理數據幀,所以可以繼續使用這種方法。
這是最容易使用的,並且在多列上運行良好 - 您只需在'duplicateated'中使用'cbind'。 – 2013-04-07 09:28:47
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
熔體(A.3,ID = C ( 「A.2」)) - > H.2; cast(h.2,a.2〜,max) 在這個例子中做了竅門,但是當我將計算機應用到我的原始數據集時,計算機的內存不足。所以沒有真正幫助我很多。 – Misha 2010-05-12 20:15:58