Search code examples
rmatrixmedianmean

How can I find the row and column of a matrix having the closest value to its mean? in R


I have a large matrix, like this one:

NCols=100
NRows=100

myMat<-matrix(runif(NCols*NRows), ncol=NCols)

I am interested in locating which row and column have the closest value to the mean or median of all values of the matrix, calculated as mean(myMat).

How could I do this in R?


Solution

  • Try this:

    set.seed(45) # just for reproducibility
    NCols <- 100
    NRows <- 100
    myMat <- matrix(runif(NCols*NRows), ncol=NCols)
    
    mat_minus_mean <- abs(myMat - mean(myMat))
    idx <- which(mat_minus_mean == min(mat_minus_mean), arr.ind = TRUE)
    #      row col
    # [1,]   5  33
    
    > myMat[idx]
    # [1] 0.5012305 # mean(myMat) is 0.5012474