Triparna Poddar
Triparna Poddar

Reputation: 428

Apply function element wise to list of matrices

I have a list of matrices/dataframes , for example:

mat = list(matrix(1:6,2,3),matrix(5:10,2,3),matrix(4:9,2,3))
mat
[[1]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

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

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

I want to get max elementwise from each matrix.

a= matrix(0,2,3)
for(i in 1:2){
  for(j in 1:3){
    a[i,j] = max(sapply(mat,function(x){x[i,j]}))
  }
}
a
     [,1] [,2] [,3]
[1,]    5    7    9
[2,]    6    8   10

This gives me the desired output but is there any way it can be done without for loop?

Upvotes: 4

Views: 267

Answers (4)

ivan866
ivan866

Reputation: 582

a <- array(unlist(mat), dim=c(2,3,3))
apply(a, c(1,2), max)

Upvotes: 3

Ma&#235;l
Ma&#235;l

Reputation: 51994

An option with Reduce and pmax:

Reduce(pmax, mat)
#     [,1] [,2] [,3]
#[1,]    5    7    9
#[2,]    6    8   10

Or, with purrr::reduce:

purrr::reduce(mat, pmax)
#     [,1] [,2] [,3]
#[1,]    5    7    9
#[2,]    6    8   10

Upvotes: 6

akrun
akrun

Reputation: 887118

We could use pmax

do.call(pmax, mat)

-output

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

Upvotes: 5

Zheyuan Li
Zheyuan Li

Reputation: 73305

apply(simplify2array(mat), c(1,2), max)
#     [,1] [,2] [,3]
#[1,]    5    7    9
#[2,]    6    8   10

Upvotes: 5

Related Questions