Reputation: 15
I have two lists of matrices and each list consists of ten 5x5 matrix:
List 1:
[[1]]
A B C D E
[1,] 1.0000000 2.0000000 1.0000000 2.0000000 1.0000000
[2,] 1.0000000 2.0000000 1.0000000 2.0000000 1.0000000
[3,] 1.0000000 2.0000000 1.0000000 2.0000000 1.0000000
[4,] 1.0000000 2.0000000 1.0000000 2.0000000 1.0000000
[5,] 1.0000000 2.0000000 1.0000000 2.0000000 1.0000000
.....
[[10]]
A B C D E
[1,] 7.0000000 3.0000000 5.0000000 2.0000000 1.0000000
[2,] 7.0000000 3.0000000 5.0000000 2.0000000 1.0000000
[3,] 7.0000000 3.0000000 5.0000000 2.0000000 1.0000000
[4,] 7.0000000 3.0000000 5.0000000 2.0000000 1.0000000
[5,] 7.0000000 3.0000000 5.0000000 2.0000000 1.0000000
List 2:
[[1]]
A B C D E
[1,] 2.0000000 2.0000000 2.0000000 2.0000000 2.0000000
[2,] 2.0000000 2.0000000 2.0000000 2.0000000 2.0000000
[3,] 2.0000000 2.0000000 2.0000000 2.0000000 2.0000000
[4,] 2.0000000 2.0000000 2.0000000 2.0000000 2.0000000
[5,] 2.0000000 2.0000000 2.0000000 2.0000000 2.0000000
.....
[[10]]
A B C D E
[1,] 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
[2,] 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
[3,] 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
[4,] 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
[5,] 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000
I summed the two lists by using lapply (see below) and got the sum result I wanted. However, they are no longer in matrices in my new list.. How do I convert them back so I can export them into CSV as matrices?
lapply code used:
lapply(seq_along(List1),function(i)
unlist(List1[i])+unlist(List2[i]))
Result:
[[1]]
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4 E1 E2 E3 E4
3 3 3 3 4 4 4 4 3 3 3 3 4 4 4 4 3 3 3 3
...
[[10]]
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4 E1 E2 E3 E4
8 8 8 8 4 4 4 4 6 6 6 6 3 3 3 3 2 2 2 2
Upvotes: 0
Views: 72
Reputation: 39707
Another option is to use MAP
to sum the matixes of two lists.
Map(`+`, List1, List2)
Upvotes: 2
Reputation: 33508
Use double bracket so that you are actually adding matrices (instead of a list of 1 matrix that you then convert to a vector with unlist):
lapply(seq_along(List1), function(i) List1[[i]] + List2[[i]])
Upvotes: 2