Search code examples
rmatrixminimum

R: Get the row and column name of the minimum element of a matrix but with minimum != 0


I've got a matrix with a lot of zeros and with positive numerical values. I want to get the row and column number for which the element is the minimal NONZERO value of the matrix.

I don't find that min() has extra options to exclude zero, so how can I handle this?


Solution

  • Seems like there could be a shorter answer but u can replace the zeros with NA and use na.rm=T

    test = matrix(c(0:9,0:9),nrow =4,ncol=5)
    test[which(test==0)] = NA
    minValue = min(test,na.rm=T) 
    rows = which(apply(test,1,min,na.rm=T)==minValue)
    cols = which(apply(test,2,min,na.rm=T)==minValue)
    

    Allows for duplicates