Home > Software design >  List (and plot) top k values of a matrix
List (and plot) top k values of a matrix

Time:08-08

How can I plot (for example with a barplot) the top 5 values in a matrix with row names and column names?

rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")

P <- matrix(3:14, nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
#     col1 col2 col3
#row1    3    4    5
#row2    6    7    8
#row3    9   10   11
#row4   12   13   14

CodePudding user response:

List top k values (with their positions) of a matrix P:

k <- 5
ij <- arrayInd(order(P, decreasing = TRUE)[1:k], dim(P))
top.k <- data.frame(x = P[ij], i = ij[, 1], j = ij[, 2])
#   x i j
#1 14 4 3
#2 13 4 2
#3 12 4 1
#4 11 3 3
#5 10 3 2

If P has row/column names, we can add them to top.k:

top.k[c("ni", "nj")] <- Map(`[`, dimnames(P), top.k[c("i", "j")])
#   x i j   ni   nj
#1 14 4 3 row4 col3
#2 13 4 2 row4 col2
#3 12 4 1 row4 col1
#4 11 3 3 row3 col3
#5 10 3 2 row3 col2

You can quickly produce a bar-chart using:

with( top.k, barplot(x, names.arg = paste(ni, nj, sep = ",")) )

but I don't know if you like its style. Again, plotting is a subjective matter.

  • Related