R Programming; Calculate median of row using FOR loop

和自甴很熟 提交于 2019-12-12 04:16:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!