How would I calculate the median (use the median function) of each row by using the FOR loop.
Using a matrix; mat = matrix(rnorm(100), 5)
Thank you in advance.
-Bill
Here is one possible solution:
mat = matrix(rnorm(100), 5)
medians_of_mat <- numeric()
for(i in 1:nrow(mat)) {
medians_of_mat[i] <- median(mat[i, ])
}
An easier way would be to use apply:
apply(mat, 1, median)
We could use rowMedians
from library(matrixStats)
library(matrixStats)
rowMedians(mat)