Reputation:
I have a list of 100 50*50 matrices in R stored in a variable called all_permutations.
> str(all_permutations)
List of 100
$ : num [1:50, 1:50] 0 0.00972 0.34989 0 0.0019 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:50] "G1" "G2" "G3" "G4" ...
.. ..$ : chr [1:50] "G1" "G2" "G3" "G4" ...
$ : num [1:50, 1:50] 0 0.00972 0.34989 0 0.0019 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:50] "G1" "G2" "G3" "G4" ...
.. ..$ : chr [1:50] "G1" "G2" "G3" "G4" ...
Is there an elegant way to obtain the mean of all these matrices without constructing double for-loops to get the average for each index across all 100 matrices? Thank you.
Upvotes: 0
Views: 81
Reputation: 44310
If you want to get the averages of the elements in each position, you would want to sum up the elements of all_permutations
and then divide by the number of elements.
If you were typing this out, you would do something like:
(all_permutations[[1]] + all_permutations[[2]] + ... ) / length(all_permutations)
Luckily, the Reduce
function can save you a lot of typing (or, more likely, a for
loop):
Reduce("+", all_permutations) / length(all_permutations)
Upvotes: 1