Home > Net >  sapply function elementwise to list of dataframes
sapply function elementwise to list of dataframes

Time:09-02

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?

CodePudding user response:

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

CodePudding user response:

We could use pmax

do.call(pmax, mat)

-output

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

CodePudding user response:

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

CodePudding user response:

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