-3

I have the dataframe df in R:

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

How to return the name of the method which gives the highest accuracy?

  • `df[which.max(df$accuracy),]` will give you the row, you might need `rownames(...)`. – r2evans Jan 16 '18 at 21:55
  • Also have a look at this [SO post](https://stackoverflow.com/questions/24237399/how-to-select-the-rows-with-maximum-values-in-each-group-with-dplyr). With `dplyr` you can use `group_by` with `top_n`, or you can use `filter` with `max`. @r2evans has a great answer too, `which.max`. – Kamil Jan 16 '18 at 21:58
  • @Kamil, if (as I inferred from the question) the "method" is identified in the row's name, then `dplyr` will silently drop the row names. (And it does not appear that the OP is trying to group them, so `group_by` was out anyway.) – r2evans Jan 16 '18 at 22:03
  • the title looks like a different question – RolandASc Jan 16 '18 at 22:59

1 Answers1

0

@r2evans and other posts have answered this already, however, here it is formally.

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
Kamil
  • 392
  • 2
  • 11
  • You might as well reference `tibble::rownames_to_column(df)`, in case the OP is relying on them. – r2evans Jan 16 '18 at 22:05