R data.table "by" for "i"

In the given data table, what will be the syntax for selecting column V1, where V2 = max (V2), grouped by V3.

For example: In the mtcars dataset, I would like to know what hp is , which corresponds to an observation equal to max (disp) , grouped by Cycle >

Here is my ugly solution using which:

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

Is there a more "data.table" way to achieve the same result?

+4
source share
3 answers

You can use .I:

mtcars[mtcars[, .I[which.max(disp)], by = cyl]$V1, .(cyl, hp)]
#   cyl  hp
#1:   6 110
#2:   4  62
#3:   8 205

or

mtcars[, hp[disp == max(disp)], by=cyl]
#   cyl  V1
#1:   6 110
#2:   4  62
#3:   8 205

And your own approach can be slightly reduced to:

mtcars[disp %in% mtcars[, max(disp), by = .(cyl)]$V1, .(cyl,hp)]
+6
source

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

, .

mtcars[, .SD[disp==max(disp), .(hp)], by = cyl]
#   cyl  hp
#1:   6 110
#2:   4  62
#3:   8 205
+7
mtcars[,ismax:=disp==max(disp),by=cyl][ismax==T, .(cyl, hp)]
   cyl  hp
1:   6 110
2:   4  62
3:   8 205

I continue to approach almost identical solutions for others. Good...

mtcars[,.SD[disp == max(disp)], by = cyl, .SDcols = c("disp", "hp")][,.(cyl, hp)]
+2
source

All Articles