1

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

juvchan
  • 6,113
  • 2
  • 22
  • 35
Foo
  • 51
  • 1
  • 5

2 Answers2

4

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)
Joachim Schork
  • 2,025
  • 3
  • 25
  • 48
0

We could use rowMedians from library(matrixStats)

library(matrixStats)
rowMedians(mat)
akrun
  • 874,273
  • 37
  • 540
  • 662