Search code examples
rmatrixcorrelationminimum

R getting the minimum value for each row in a matrix, and returning the row and column name


I have a matrix like so:

enter image description here

Only in reality it is hundreds or thousands of values.

What I need to do is return the minimum value for each row, along with the row/col name.

So for row 1 in the example, "BAC", the minimum is 0.92 for BAC/CSCO, so I need to return something like:

BAC/CSCO 0.92

And then repeat this for each row in the matrix.

Assistance is greatly appreciated. I think apply is the trick, but I can't quite get the right combination.


Solution

  • X <- matrix(runif(20), nrow=4)
    rownames(X) <- paste0("foo", seq(nrow(X)))
    colnames(X) <- paste0("bar", seq(ncol(X)))
    
    result <- t(sapply(seq(nrow(X)), function(i) {
      j <- which.min(X[i,])
      c(paste(rownames(X)[i], colnames(X)[j], sep='/'), X[i,j])
    }))
    
    print(X)
    print(result)
    

    will give you:

              bar1      bar2       bar3       bar4      bar5
    foo1 0.2085419 0.6290522 0.12730378 0.17775105 0.3239684
    foo2 0.8061464 0.7948392 0.09330563 0.06698921 0.5557932
    foo3 0.1790950 0.7788139 0.35787944 0.39117325 0.2578457
    foo4 0.9099254 0.4048508 0.54791272 0.38674301 0.3272156
    

    and

         [,1]        [,2]                
    [1,] "foo1/bar3" "0.127303782384843" 
    [2,] "foo2/bar4" "0.0669892099685967"
    [3,] "foo3/bar1" "0.179094966035336" 
    [4,] "foo4/bar5" "0.327215566998348"