Reputation: 1232
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
Upvotes: 2
Views: 14473
Reputation: 46876
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))
Upvotes: 1
Reputation: 57696
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.
Upvotes: 4