matrixStats
matrixStats copied to clipboard
WISH: rowWhichMin(x) (and also with cols)
A function that returns the index of the minimum value equivalent to apply(A,1,which.min)
If implemented, the functions should be:
colWhichMins(x)
rowWhichMins(x)
and likely also:
colWhichMaxs(x)
rowWhichMaxs(x)
while at it.
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)))
Just a comment: In R base, the function max.col
seems to be very efficient already. It does a "rowWhichMaxs"
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.