问题
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
回答1:
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)
回答2:
We could use rowMedians
from library(matrixStats)
library(matrixStats)
rowMedians(mat)
来源:https://stackoverflow.com/questions/35955409/r-programming-calculate-median-of-row-using-for-loop