2
votes

Suppose I have a matrix like the example below called m1:

m1<-matrix(6:1,nrow=3,ncol=2)
     [,1] [,2]
[1,]    6    3
[2,]    5    2
[3,]    4    1

How do I get the index row for the minimum value of each column? I know which.min() will return the column index value for each row.

The output should be: 3 and 3 because the minimum for column [,1] is 4 corresponding to row [3,] and the minimum for column [,2] is 1 corresponding row [3,].

1

1 Answers

2
votes

If we need column wise index use apply with MARGIN=2 and apply the which.min

apply(m1, 2, which.min)
#[1] 3 3

If 1 column at a time is needed:

apply(as.matrix(m1[,1, drop = FALSE]), 2, which.min)

If we check ?Extract, the default usage is

x[i, j, ... , drop = TRUE]

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.

To avoid getting dimensions dropped, use drop = FALSE

If we need the min values of each row

do.call(pmin, as.data.frame(m1))

Or

apply(m1, 2, min)

Or

library(matrixStats)
rowMins(m1)

data

m1 <- matrix(6:1,nrow=3,ncol=2)