Assume I have a data.table
containing some baseball players:
library(plyr)
library(data.table)
bdt <- as.data.table(baseball)
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))
What's the equivalent code for data.table
?
I tried:
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
This works:
bdt[, .SD[g == max(g)], by = id]
But it's is only 30% faster than plyr
, suggesting it's probably not idiomatic.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…