0

rows, disp, hp我可以使用函数在 mtcars 数据集中找到最大值sapply,分别给出 472 335:

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

现在我想要cyl这些值,即找到cyl最大值的汽车sapply(list(mtcars$disp,mtcars$hp),max,na.rm=TRUE)

我应该使用哪个功能?我尝试失败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))
4

2 回答 2

1
library(dplyr)
filter(mtcars, hp==max(hp) | disp == max(disp))$cyl
于 2017-11-05T10:30:06.893 回答
0

data.table 解决方案是:

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
于 2018-05-29T10:30:05.193 回答