I have a huge matrix
in which I would like to replace the values inferior to the mean (or median) of each column with an NA
.
For example, with this matrix
:
set.seed(1)
ex <- matrix(data = round(runif(12), 1), nrow = 4, ncol = 3)
ex
[,1] [,2] [,3]
[1,] 0.3 0.2 0.6
[2,] 0.4 0.9 0.1
[3,] 0.6 0.9 0.2
[4,] 0.9 0.7 0.2
I would like to get:
for(i in 1:ncol(ex)){
ex[, i][ex[, i] < colMeans(ex)[i]] <- NA
}
ex
[,1] [,2] [,3]
[1,] NA NA 0.6
[2,] NA 0.9 NA
[3,] 0.6 0.9 NA
[4,] 0.9 0.7 NA
The code above uses a for-loop and I would like to have a faster vectorized version.
We can use
sweep
.Or with some transposing
Since it's a matrix, we can also use
apply
columnwise