In R, getting top 10 values of matrix and outputting row names to vector

13,728

Solution 1

Things are a little simpler here because you have a single-column matrix which can also be treated as a vector.

rownames(x)[order(x, decreasing=TRUE)][1:10]

This returns the top 10 indices of x in decreasing order, extracts the corresponding elements of the names of x.

Solution 2

Here's some data

set.seed(123)
x =  matrix(runif(26), 26, dimnames=list(LETTERS, NULL))

Generate a named vector to avoid bookkeeping errors, exploiting the fact that R will drop a one-dimensional matrix to a vector with names of the corresponding dimension)

o = order(x, decreasing=TRUE)[1:10]
Result = x[o,]   # _named_ numeric

Use a dotplot for better presentation of values, especially facilitating comparison of magnitudes

library(lattice)
dotplot(Result, type=c("l", "p"), cex=2, xlim=c(0, 1))

or in alphabetical order (no bookkeeping worries!)

o = order(names(Result))
dotplot(Result[o], type=c("l", "p"), cex=2, xlim=c(0, 1))
Share:
13,728
timothyjgraham
Author by

timothyjgraham

I am a research assistant and PhD student at University of Queensland (Australia). My research interests are digital sociology, social network analysis, social studies of technology.

Updated on June 14, 2022

Comments

  • timothyjgraham
    timothyjgraham almost 2 years

    How can I extract the top ten values from a single column matrix, and output the corresponding row names to a vector?

    I want to put labels on a pie chart I have generated, but for the life of me can't figure out how.

    Many thanks.

    Tim