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
?
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