RudiSophieson RudiSophieson - 2 months ago 7
R Question

Standard deviation over a list of matrices in R

I have a list in which each element is a matrix.

set.seed(123)

m1 <- matrix(sample(c(1:10), size = 9, replace = TRUE), ncol = 3, nrow = 3)
m2 <- matrix(sample(c(1:10), size = 9, replace = TRUE), ncol = 3, nrow = 3)
m3 <- matrix(sample(c(1:10), size = 9, replace = TRUE), ncol = 3, nrow = 3)

m <- list(m1, m2, m3)
m
[[1]]
[,1] [,2] [,3]
[1,] 3 9 6
[2,] 8 10 9
[3,] 5 1 6

[[2]]
[,1] [,2] [,3]
[1,] 5 7 9
[2,] 10 6 3
[3,] 5 2 1

[[3]]
[,1] [,2] [,3]
[1,] 4 7 7
[2,] 10 7 8
[3,] 9 10 6


I want to calculate the standard deviation of each pair considering all three matrices. So for cell [1,1] the standard deviation would be:

sd(c(3, 5, 4))


My final matrix should look like this:

[,1] [,2] [,3]
[1,] 1.00 1.15 1.53
[2,] 1.15 2.08 3.21
[3,] 2.31 4.93 2.89


How can I achieve this in R without a loop over all three matrices?

Many thanks in advance.

Answer

It is better to convert this to array by unlisting the list to a vector, convert it to a 3D array and get the sd with apply

round(apply(array(unlist(m), c(3, 3, 3)), c(1,2), sd),2)
#    [,1] [,2] [,3]
#[1,] 1.00 1.15 1.53
#[2,] 1.15 2.08 3.21
#[3,] 2.31 4.93 2.89
Comments