Search code examples
rmatrixminimum

R: row number of the minimum value in each column


I've got a matrix and now I search for the minimum value of EACH column. I've got de next code:

error.mars1[which(error.mars1==0)] = NA
minValue = min(error.mars1[,2],na.rm=T)

I've used NA because I want a nonzero minimum value. So this was to get the mean of column 2. But now I want the row number for which this is the minimum value. Can someone help me?


Solution

  • Generally what you are asking about is given by:

    apply(error.mars1, 2, function(x) which(x == min(x, na.rm=TRUE)))
    

    Alternatively:

    apply(error.mars1, 2, which.min)