Reputation: 15
I have a list with ten 5x5 matrices and I would like to get the maximum of each column within each matrix. Example of my list is below:
My List:
[[1]]
A B C D E
[1,] 30 40 60 12 7
[2,] 14 30 50 25 2
[3,] 53 1 50 54 50
[4,] 61 200 50 33 7
[5,] 73 88 50 33 8
.....
[[10]]
A B C D E
[1,] 2 40 60 6 7
[2,] 6 30 2 25 2
[3,] 9 1 40 54 50
[4,] 55 2 80 1 100
[5,] 20 88 1 200 8
Result I need is: My List showing maximum at each column of each matrix and the result list will have ten 1x5 matrices:
[[1]]
A B C D E
[1,] 73 200 60 54 50
.....
[[10]]
A B C D E
[1,] 55 88 80 200 100
I used apply but I know I am missing something to tell it to go through each column of each matrix..
apply(My List, 2, max, na.rm = TRUE)
The error message I got was:
dim(X) must have a positive length
Upvotes: 1
Views: 495
Reputation: 887048
We need lapply
with apply
i.e. loop over the list
with lapply
, then loop across the columns (MARGIN = 2
) of the matrix
within each list
with apply
lapply(MyList, function(x) apply(x, MARGIN = 2,
FUN = max, na.rm = TRUE))
-output
[[1]]
A B C D E
73 200 60 54 50
[[2]]
A B C D E
55 88 80 100 100
Or use colMaxs
from matrixStats
library(matrixStats)
lapply(MyList, colMaxs, na.rm = TRUE)
[[1]]
[1] 73 200 60 54 50
[[2]]
[1] 55 88 80 100 100
MyList <- list(structure(c(30, 14, 53, 61, 73, 40, 30, 1, 200, 88, 60,
50, 50, 50, 50, 12, 25, 54, 33, 33, 7, 2, 50, 7, 8), .Dim = c(5L,
5L), .Dimnames = list(NULL, c("A", "B", "C", "D", "E"))), structure(c(2,
6, 9, 55, 20, 40, 30, 1, 2, 88, 60, 2, 40, 80, 1, 6, 25, 54,
1, 100, 7, 2, 50, 100, 8), .Dim = c(5L, 5L), .Dimnames = list(
NULL, c("A", "B", "C", "D", "E"))))
Upvotes: 1