将函数元素明智地应用于矩阵列表

Tri*_*dar 4 r list max matrix sapply

我有一个矩阵/数据帧列表,例如:

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
Run Code Online (Sandbox Code Playgroud)

我想从每个矩阵中获取最大元素。

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
Run Code Online (Sandbox Code Playgroud)

这给了我想要的输出,但是有什么方法可以在没有 for 循环的情况下完成它?

Maë*_*aël 6

Reduce带有和 的选项pmax

Reduce(pmax, mat)
#     [,1] [,2] [,3]
#[1,]    5    7    9
#[2,]    6    8   10
Run Code Online (Sandbox Code Playgroud)

或者,与purrr::reduce

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


李哲源*_*李哲源 5

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


akr*_*run 5

我们可以使用pmax

do.call(pmax, mat)
Run Code Online (Sandbox Code Playgroud)

-输出

     [,1] [,2] [,3]
[1,]    5    7    9
[2,]    6    8   10
Run Code Online (Sandbox Code Playgroud)