使用data.table按组对与最大值对应的行进行子集 [英] Subset rows corresponding to max value by group using data.table

查看:63
本文介绍了使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆