How do I find the row names of the top 10 highest values in column X

head(sort(df[,"X"], decreasing=TRUE), n=10)
#this returns the top 10 highest values in column X, but I want the row names of those values in column X. I've tried rownames but it comes up with NULL or NA

1 Like

Hi,

Here is one implementation:

#Fake data
myData = data.frame(x = 1:100, y = runif(100))
rownames(myData) = paste0("row", 1:nrow(myData))

#Filter
rownames(myData[order(myData$y, decreasing = T),])[1:10]

And this is a tidyverse implementation:

library(tidyverse)

#Fake data
myData = data.frame(x = 1:100, y = runif(100))
rownames(myData) = paste0("row", 1:nrow(myData))

#Filter
myData %>% rownames_to_column("rowNames") %>% 
arrange(desc(y)) %>% slice(1:10) %>% pull(rowNames)

Hope this helps,
PJ

3 Likes

In the tidyverse, you can also use the top_n function to save a little typing:

library(tidvyverse)

mtcars %>% rownames_to_column() %>% top_n(10, mpg) %>% pull(rowname)
 [1] "Datsun 710"     "Merc 240D"      "Merc 230"       "Fiat 128"       "Honda Civic"    "Toyota Corolla"
 [7] "Toyota Corona"  "Fiat X1-9"      "Porsche 914-2"  "Lotus Europa"  
 iris %>% rownames_to_column() %>% top_n(10, Petal.Width) %>% pull(rowname)
 [1] "101" "110" "115" "116" "119" "121" "136" "137" "141" "142" "144" "145" "146" "149"
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.