Bhavana
Bhavana

Reputation: 15

Fetch values of other columns which have max value in given column

I can find max values of rows, disp, hp in mtcars dataset using sapply function, which gives 472 335 respectively:

sapply(list(mtcars$disp,mtcars$hp), max, na.rm=TRUE)

Now I want cyl for these values, i.e. cyl of cars where maximum value of sapply(list(mtcars$disp,mtcars$hp),max,na.rm=TRUE) is found.

Which function should I be using? I tried unsuccessfully with which,rownames,colnames:

mtcars(which(sapply(list(mtcars$disp,mtcars$hp),max,na.rm=TRUE)))
rownames(which(sapply(list(mtcars$disp,mtcars$hp),max,na.rm=TRUE))))
mtcars$cyl(sapply(list(mtcars$disp,mtcars$hp),max,na.rm=TRUE))

Upvotes: 0

Views: 77

Answers (2)

smci
smci

Reputation: 33938

And the data.table solution is:

require(data.table)
mtcars <- as.data.table(mtcars)

mtcars[hp==max(hp) | disp==max(disp)]
    mpg cyl disp  hp drat   wt  qsec vs am gear carb
1: 10.4   8  472 205 2.93 5.25 17.98  0  0    3    4
2: 15.0   8  301 335 3.54 3.57 14.60  0  1    5    8

#  if you want to get one column, e.g. 'cyl'
mtcars[hp==max(hp) | disp == max(disp), cyl]
[1] 8 8

# if you want to get several columns, do either of:
mtcars[hp==max(hp) | disp == max(disp), .(cyl,qsec)]
mtcars[hp==max(hp) | disp == max(disp), list(cyl,qsec)]
   cyl  qsec
1:   8 17.98
2:   8 14.60

Upvotes: 0

akond
akond

Reputation: 16035

library(dplyr)
filter(mtcars, hp==max(hp) | disp == max(disp))$cyl

Upvotes: 1

Related Questions