4
votes

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.

2

2 Answers

5
votes

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
1
votes

Another option is

matrix(apply(sapply(1:9, function(x) unlist(m)[seq(x, length(unlist(m)), 9)]), 2, sd), 
                                                                              ncol = 3)

#       [,1]     [,2]     [,3]
#[1,] 1.000000 1.154701 1.527525
#[2,] 1.154701 2.081666 3.214550
#[3,] 2.309401 4.932883 2.886751