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,]
返回的是列表索引,而不是整个数据框的索引。
我试图为每个 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,]
返回的是列表索引,而不是整个数据框的索引。
我试图为每个 a.2
子组返回最大的 b.2
值。如何高效地实现?
ddply
和ave
方法都很耗费资源。在当前问题中(67,608行,有四列用于定义唯一键),ave
由于内存不足而失败。 tapply
是一个方便的选择,但我通常需要选择每个唯一键最大(或最小)某值的所有整行(通常由多个列定义)。我找到的最佳解决方案是排序,然后使用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
可以用于数据框,因此可以继续使用这种方法。
duplicated
内部使用cbind
。 - Josephine Moellerlibrary(plyr)
ddply(a.3, "a.2", subset, b.2 == max(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,]
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
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