如何找到在给定行中保持最小值的列?

时间:2018-01-16 21:52:23

标签: r dataframe

我在R中有数据框df:

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

如何返回提供最高精度的方法名称?

1 个答案:

答案 0 :(得分:0)

@ 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