【问题标题】:how to find the column which hold the minimum value in a given row?如何找到在给定行中保存最小值的列?
【发布时间】:2025-12-18 17:55:01
【问题描述】:

我在 R 中有数据框 df:

          accuracy
method A   3
method B   6
method C   2
method D   8
method E   1

如何返回准确率最高的方法名?

【问题讨论】:

  • df[which.max(df$accuracy),] 会给你行,你可能需要rownames(...)
  • 也看看这个SO post。对于dplyr,您可以将group_bytop_n 一起使用,或者您可以将filtermax 一起使用。 @r2evans 也有很好的答案,which.max
  • @Kamil,如果(正如我从问题中推断的那样)在行名中标识了“方法”,那么dplyr 将默默地删除行名。 (而且看起来 OP 并没有尝试对它们进行分组,所以 group_by 无论如何都出来了。)
  • 标题看起来像一个不同的问题

标签: r dataframe


【解决方案1】:

@r2evans 和 other posts 已经回答了这个问题,但是,这里是正式的。

df <- data.frame(method = letters[1:5], accuracy = c(2,6,2,8,1),
                 stringsAsFactors = F)
> df
  method accuracy
1      a        2
2      b        6
3      c        2
4      d        8
5      e        1

# method 1, get the row index of the max value for a column
> which.max(df$accuracy)
[1] 4

# method 2, return the entire row where the column accuracy
# has a maximal value
library(dplyr)
df %>% 
  filter(accuracy == max(accuracy))

  method accuracy
1      d        8

【讨论】:

  • 你不妨参考tibble::rownames_to_column(df),以防 OP 依赖它们。
最近更新 更多