简体   繁体   中英

R: place of min / max in a matrix

I have a table of 10 variables and 193 observations (10 columns and 193 rows)

now I found for each column the min/max with

#min
minINT <- apply(INT, 1, min)

#max
maxINT <- apply(INT, 1, max)

How can I find now the "place" of the min/max value in each row? (eg row 1 = 3 variable ; or row 156 = 7 variable)

Thanks!

You contradict yourself in your question: is it the maximum in each row or in each column that you want? I assume in the following that you want the maximum per row, since this is what your code is doing.

which.min() and which.max() return the position of the minimum and maximum of a vector, respectively. You can use them with apply() :

#min
minINT_pos <- apply(INT, 1, which.min)

#max
maxINT_pos <- apply(INT, 1, which.max)

If there is a tie, that is, if several elements take the maximum or minimum value, this will return the position of the first of these elements (thanks to Richard Scriven for the comment).

There is also the funtion max.col() that returns the index of the maximum in each row.

maxINT_pos <- max.col(INT)

This function differs from which.max() in that you can specify what is done in the case of a tie. By default, it picks on of the values randomly, but you can also set ties.method = "first" or ties.method = "last" to pick the first (as does which.max() ) or the last element.

In addition, max.col() is faster than which.max() with apply() :

library(microbenchmark)
m <- matrix(runif(1000), ncol = 10)
microbenchmark(apply(m, 1, which.max), max.col(m))
## Unit: microseconds
##                    expr     min       lq      mean   median       uq     max neval cld
##  apply(m, 1, which.max) 190.883 200.7075 230.56125 211.5590 223.3115 529.712   100   b
##              max.col(m)  53.316  57.0905  69.54417  61.3835  71.2555 204.897   100  a 

min.col() does not exist, but you can easily get the minima by multiplying the matrix by -1 (thanks to nicola for the hint):

minINT_pos <- max.col(-INT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM