roschu
roschu

Reputation: 776

How to perform element-wise statistics over numerous (distance) matrices

I have several thousand distance matrices (converted from a matrix using as.dist()) and would like to compute the mean, sd, median etc for each matrix element.

To illustrate:

Matrix.A

1
7 1
5 2 1

Matrix.B

2  
3 4
1 1 3

etc...

For example, if I would like to have the sum of the individual elements I could do:

Sum.Matrix <- Matrix.A + Matrix.B

Sum.Matrix

3
10 5
6 3 4

But what if I have thousands of these matrices? And how can I compute not just the sum for each element but also means, sd etc? All matrices are stored in a single list.

Upvotes: 0

Views: 140

Answers (1)

akrun
akrun

Reputation: 887511

Try

lst2 <- lapply(lst1, as.matrix)
dim1 <- sapply(lst2, dim)[,1]
l <- length(lst1)
ar1 <- array(unlist(lst2), dim=c(dim1, l)) 

as.dist(apply(ar1, 1:2, sum))
as.dist(apply(ar1, 1:2, mean))
as.dist(apply(ar1, 1:2, sd))

data

set.seed(24)
lst1 <- lapply(1:4, function(i) dist(sample(1:10,4, replace=TRUE)))

Upvotes: 2

Related Questions