I want my answer to be formatted like. Rows containing indices of top 5 values in descending order to be stored in another matrix:
R1:6, 3, 7, 5, 10
R2:7, 1, 2, 3, 4
R3:3, 1, 2, 4, 5
and so on.
I want my answer to be formatted like. Rows containing indices of top 5 values in descending order to be stored in another matrix:
R1:6, 3, 7, 5, 10
R2:7, 1, 2, 3, 4
R3:3, 1, 2, 4, 5
and so on.
We can loop over the rows using apply
with MARGIN=1
, order
the elements, select the first 5 element and transpose the matrix.
t(apply(m1, 1, FUN= function(x) order(-x)[1:5]))
# [,1] [,2] [,3] [,4] [,5]
#[1,] 6 3 7 5 10
#[2,] 7 1 2 3 4
#[3,] 3 1 2 4 5
NOTE: Here, I am using only the first 3 rows of the image data provided by the OP.
m1 <- structure(c(0.001371742, 0.058823529, 0.428571429, 0, 0, 0,
0.10973937,
0, 0.71428571, 0, 0, 0, 0.04115226, 0, 0, 0.25377229, 0, 0, 0.10013717,
0.91176471, 0, 0, 0, 0, 0, 0, 0, 0.006858711, 0, 0),
.Dim = c(3L,
10L), .Dimnames = list(NULL, c("V1", "V2", "V3", "V4", "V5",
"V6", "V7", "V8", "V9", "V10")))