midde
midde

Reputation: 35

How does one lookup of max value in matrix?

I have a table that looks like this:

       1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
  586  0 0 0 1 0 0 0 1 3  1  0  1  0  0  0  0  0  1  0  2  0  3  0  0  0  4  0  1  2  0
  637  0 0 0 0 0 0 2 3 2  2  0  4  0  0  0  0  1  0  0  2  0  1  1  1  0  0  0  0  0  1
  989  0 0 1 0 0 0 2 1 0  0  0  2  1  0  0  1  2  1  0  3  0  2  0  1  1  0  1  0  1  0
  1081 0 0 0 1 0 0 1 0 1  1  0  0  2  0  0  0  0  0  0  3  0  5  0  0  2  1  0  1  1  1
  2922 0 1 1 1 0 0 0 2 1  0  0  0  2  0  0  0  1  1  0  1  0  3  1  1  2  0  0  1  0  1
  3032 0 1 0 0 0 0 0 3 0  0  1  0  2  1  0  1  0  1  1  0  0  3  1  1  1  1  0  0  1  1

Numbers 1 to 30 in the first row are my labels, and the columns are my items. I would like to find, for each item, the label with the most counts. E.g. 586 has 4 counts of 26, which is the highest number in that row, so for 586, I would like to assign 26.

I am able to get the maximum value for each row with max(table1[1,])), which gets me the maximum value for first row, but doesn't get me the label it corresponds to, but I don't know how to proceed. All help is appreciated!

dput:

structure(c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 
0L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 2L, 2L, 1L, 0L, 0L, 1L, 3L, 1L, 
0L, 2L, 3L, 3L, 2L, 0L, 1L, 1L, 0L, 1L, 2L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 1L, 1L, 4L, 2L, 0L, 0L, 0L, 0L, 0L, 1L, 2L, 2L, 
2L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 
0L, 0L, 1L, 0L, 1L, 2L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 
0L, 0L, 0L, 0L, 1L, 2L, 2L, 3L, 3L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 3L, 1L, 2L, 5L, 3L, 3L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 
0L, 1L, 1L, 0L, 0L, 1L, 2L, 2L, 1L, 4L, 0L, 0L, 1L, 0L, 1L, 0L, 
0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 2L, 0L, 1L, 1L, 0L, 
1L, 0L, 1L, 0L, 1L, 1L, 1L), .Dim = c(6L, 30L), .Dimnames = structure(list(
    c("586", "637", "989", "1081", "2922", "3032"), c("1", "2", 
    "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
    "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", 
    "24", "25", "26", "27", "28", "29", "30")), .Names = c("", 
"")))

Upvotes: 1

Views: 296

Answers (2)

CHP
CHP

Reputation: 17189

max.col will give you vector of column numbers which correspond to maximum value for each row.

> max.col(df, tie='first')
[1] 26 12 20 22 22 8

You can use that vector to get column names for each row.

> colnames(df)[max.col(df, tie='first')]
[1] "26" "12" "20" "22" "22" "8"

Upvotes: 8

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193507

Perhaps you are looking for which.max. Assuming your matrix is called "temp":

> apply(temp, 1, which.max)
 586  637  989 1081 2922 3032 
  26   12   20   22   22    8 

apply with MARGIN = 1 (the second argument) will apply a function by row.

Upvotes: 5

Related Questions