matrixStats icon indicating copy to clipboard operation
matrixStats copied to clipboard

WISH: rowWhichMin(x) (and also with cols)

Open arubio2 opened this issue 8 years ago • 4 comments

A function that returns the index of the minimum value equivalent to apply(A,1,which.min)

arubio2 avatar Dec 08 '15 22:12 arubio2

If implemented, the functions should be:

colWhichMins(x)
rowWhichMins(x)

and likely also:

colWhichMaxs(x)
rowWhichMaxs(x)

while at it.

HenrikBengtsson avatar Apr 06 '16 20:04 HenrikBengtsson

For the time being, when I needed rowWhichMaxs() functionality, I did this (piggy-backing on rowRanks()), which speeds up things about 10-fold relative to an apply()-based solution:

as.vector((rowRanks(x) == ncol(x)) %*% seq_len(ncol(x)))

JoshOBrien avatar Jan 19 '17 18:01 JoshOBrien

Just a comment: In R base, the function max.col seems to be very efficient already. It does a "rowWhichMaxs"

mayer79 avatar Mar 06 '17 10:03 mayer79

I also needed this function and ended up with a

((which(t(x==1)) - 1) %% ncol(x)) + 1

version of this. The trick is essentially to cast x to a vector and then fix the indices to be by row. In this case I do know that only one element is 1 in each row! This is also 10x faster than the respective apply approach.

wds15 avatar Aug 10 '22 14:08 wds15