Home > Blockchain >  How to find the name of a row that has the highest value in a column
How to find the name of a row that has the highest value in a column

Time:11-02

i am trying to find the name of the row which shows the highest value of a singular column in my data frame, I have tried using

rownames(which.max(df[,1])) and

rownames(df)[apply(df,1,which.ax)]

however the first piece of code only gives me the word 'NULL' and the second piece of code provides me a long list of many row names.

using which.max(df[,1]) provides me with the correct number, but not the corresponding name of the row i am looking for.

Thanks for any help

CodePudding user response:

We may do

 rownames(df)[which.max(df[[1]])]

If we want for each column

sapply(df, \(x) row.names(df)[which.max(x)])

CodePudding user response:

Another option using max.col by first transposing the dataframe like this:

df <- data.frame(V1 = c(1,2,3,4,5),
                 row.names = c(1,2,3,4,5))
df
#>   V1
#> 1  1
#> 2  2
#> 3  3
#> 4  4
#> 5  5
rownames(df)[max.col(t(df))]
#> [1] "5"

Created on 2022-11-01 with reprex v2.0.2

  • Related