【问题标题】:How to find the highest number of a column and print two columns of that row in R?如何在R中找到一列的最高编号并打印该行的两列?
【发布时间】:2020-04-17 23:23:27
【问题描述】:

如何获取 column2 的最大值,然后打印该行的 column1 AND column2

Column1 Column2
test1    2
test2    9
test3    3
test5    4.5

那么,由于 第 2 列 的值最高,如何打印第二行?

请记住,数据集中还有更多列,但我不想全部打印出来。

编辑: 已经尝试获取该列的最高值,但我想打印该行的两列(不是所有列);下面的一个给了我包含大约 35 列的整行:

subset(df1, Column2 == max(Column2))

【问题讨论】:

    标签: r dataset max


    【解决方案1】:

    我们可以使用slice - 返回找到max 值的第一行

    library(dplyr)
    df1 %>%
      select(Column1, Column2) %>%
      slice(which.max(Column2))
    

    或者使用来自base Rsubset - 返回存在max 值的所有行

    subset(df1, Column2 == max(Column2), select = c(Column1, Column2))
    

    which.max - 返回找到最大值的第一行

    df1[which.max(df1$Column2),c("Column1", "Column2"), drop = FALSE]
    

    【讨论】:

    • 这就是我已经尝试过的,但我只想打印两列,因为我已经说过我有很多列。因此,获取 column2 的最大值并打印该行的 Column1 和 Column2。
    • @CoolSolutions 感谢您的解释。我通过在两者之间添加select 来更新帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2023-04-01
    • 2021-06-26
    • 2019-10-15
    相关资源
    最近更新 更多