在给定的data.table中,选择列V1的语法是什么,其中V2 = max(V2),按V3分组.
例如:在mtcars数据集中,我想找出与观察相对应的hp是多少(max),由cyl分组
这是我的不合理的解决方案,使用其中:
mtcars <- data.table(mtcars)
mtcars[which(mtcars$disp %in% mtcars[, max(disp), by = .(cyl)]$V1), .(cyl,hp)]
cyl hp
1: 6 110
2: 4 62
3: 8 205
Run Code Online (Sandbox Code Playgroud)
是否有更"数据表"的方式来实现相同的结果?
我们可以尝试加入
mtcars[mtcars[, list(disp=max(disp)), by = cyl],
on = c('cyl', 'disp')][, c('cyl', 'hp'), with=FALSE]
# cyl hp
#1: 6 110
#2: 4 62
#3: 8 205
Run Code Online (Sandbox Code Playgroud)
或者这是一个较短的版本来获得预期的输出.
mtcars[, .SD[disp==max(disp), .(hp)], by = cyl]
# cyl hp
#1: 6 110
#2: 4 62
#3: 8 205
Run Code Online (Sandbox Code Playgroud)
你可以使用.I:
mtcars[mtcars[, .I[which.max(disp)], by = cyl]$V1, .(cyl, hp)]
# cyl hp
#1: 6 110
#2: 4 62
#3: 8 205
Run Code Online (Sandbox Code Playgroud)
要么
mtcars[, hp[disp == max(disp)], by=cyl]
# cyl V1
#1: 6 110
#2: 4 62
#3: 8 205
Run Code Online (Sandbox Code Playgroud)
您自己的方法可以略微缩短为:
mtcars[disp %in% mtcars[, max(disp), by = .(cyl)]$V1, .(cyl,hp)]
Run Code Online (Sandbox Code Playgroud)