Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise median of list of matrices in R

Tags:

r

matrix

Given a list of matrices:

temp <- list(matrix(c(1,8,3,400), 2), 
    matrix(c(5,2,300,14),2), 
    matrix(c(100,200,12,4),2)
)
temp
# [[1]]
#      [,1] [,2]
# [1,]    1    3
# [2,]    8  400
#
# [[2]]
#      [,1] [,2]
# [1,]    5  300
# [2,]    2   14
#
# [[3]]
#      [,1] [,2]
# [1,]  100   12
# [2,]  200    4

I want the element-wise median of the matrices:

     [,1] [,2]
[1,]    5   12
[2,]    8   14

Can this be done without explicit for loops?

like image 321
ved Avatar asked Dec 06 '25 01:12

ved


1 Answers

First, put it into an array:

library(abind)
a <- do.call(abind, c(temp, list(along=3)))

Then use apply:

apply(a, 1:2, median)
#      [,1] [,2]
# [1,]    5   12
# [2,]    8   14

As @RichardScriven suggests, you can also build a without the abind package:

a <- array(unlist(temp), c(2, 2, 3))
# or
a <- array(unlist(temp), c(dim(temp[[1]]), length(temp)))
like image 94
Frank Avatar answered Dec 08 '25 15:12

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!