【问题标题】:Fetch values of other columns which have max value in given column获取在给定列中具有最大值的其他列的值
【发布时间】:2017-11-05 10:21:45
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: r max sapply argmax


    【解决方案1】:
    library(dplyr)
    filter(mtcars, hp==max(hp) | disp == max(disp))$cyl
    

    【讨论】:

    • 您好,有没有一种可能的方法来获取其他列的值以获取 sapply 获取的结果?
    • 当然,最后去掉$cyl。
    【解决方案2】:

    而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
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2017-12-18
      • 1970-01-01
      • 2017-10-11
      • 2014-06-11
      • 2014-04-23
      • 2023-03-08
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多