I have a matrix of 366*1055 dimension. I wanted to subtract each value (each row consists of 1055 elements) in a row with its respective rowMedian value. How to go about it ??
Asked
Active
Viewed 325 times
2 Answers
2
Using the base package. The matrix m1 is from akrun's answer.
Explanation
We can use the apply
function to apply a function, median
in this case, to every row in the matrix m1. We set the second argument to 1 to indicate that the function will be applied over rows (row-by-row). The apply functions are very useful in R. For more details, type ?apply
in the console or check this thorough answer by Joran.
m1 - apply(m1, 1, median)
Output
[,1] [,2] [,3] [,4] [,5]
[1,] -1 3 -3 0 1
[2,] -1 0 2 -1 0
[3,] 1 0 1 -3 -4
[4,] 3 4 -1 -1 0
[5,] 3 0 -1 6 -3
[6,] 3 3 0 -4 -6
[7,] 0 -1 -2 5 1
[8,] 2 -5 0 1 -2
[9,] 2 -1 0 0 -4
[10,] 0 -1 -2 7 1
-
While this answer is correct, it would be worth adding some explanatory text so that later readers with less knowledge can understand WHY this is correct and how it works. – kdopen Oct 15 '15 at 19:18
-
@kdopen You're right. I've just edited my answer to provide an explanation and a couple of references. Thank you. – mpalanco Oct 15 '15 at 20:40
1
We can use rowMedians
from matrixStats
to calculate the rowwise median
and subtract it from the matrix 'm1'.
library(matrixStats)
m1 - rowMedians(m1, na.rm=TRUE)
data
set.seed(24)
m1 <- matrix(sample(0:9, 10*5, replace=TRUE), ncol=5)

akrun
- 874,273
- 37
- 540
- 662