使用data.table按组对应于最大值的子集行 [英] Subset rows corresponding to max value by group using data.table
问题描述
假设我有一个包含一些棒球运动员的 data.table
:
Assume I have a data.table
containing some baseball players:
library(plyr)
library(data.table)
bdt <- as.data.table(baseball)
对于每个组(由玩家id"给出),我想选择与最大游戏数g"相对应的行.这在 plyr
中很简单:
For each group (given by player 'id'), I want to select rows corresponding to the maximum number of games 'g'. This is straightforward in plyr
:
ddply(baseball, "id", subset, g == max(g))
data.table
的等效代码是什么?
我试过了:
setkey(bdt, "id")
bdt[g == max(g)] # only one row
bdt[g == max(g), by = id] # Error: 'by' or 'keyby' is supplied but not j
bdt[, .SD[g == max(g)]] # only one row
这行得通:
bdt[, .SD[g == max(g)], by = id]
但它只比 plyr
快 30%,这表明它可能不是惯用的.
But it's is only 30% faster than plyr
, suggesting it's probably not idiomatic.
推荐答案
这是快速的 data.table
方式:
bdt[bdt[, .I[g == max(g)], by = id]$V1]
这避免了构造 .SD
,这是表达式中的瓶颈.
This avoids constructing .SD
, which is the bottleneck in your expressions.
实际上,OP 运行缓慢的主要原因不仅在于它包含 .SD
,还在于它以特定方式使用它- 通过调用 [.data.table
,目前它的开销很大,因此在循环中运行它(当一个 by
执行时)会累积非常大的惩罚.
edit: Actually, the main reason the OP is slow is not just that it has .SD
in it, but the fact that it uses it in a particular way - by calling [.data.table
, which at the moment has a huge overhead, so running it in a loop (when one does a by
) accumulates a very large penalty.
这篇关于使用data.table按组对应于最大值的子集行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!