Sum of a list of matrices in R

守給你的承諾、 提交于 2020-08-10 05:27:42

问题


I am trying to put a list of matrices together in a list and then do summation inside of each list. Below are the simple example of the codes:

Let's say if I have 4 matrices:

x1 <- matrix(1:9, nrow = 3)
x2 <- matrix(2:10, nrow = 3)
x3 <- matrix(3:11, nrow = 3)
x4 <- matrix(4:12, nrow = 3)

And I want to put them into a list() in a way like this:

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

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


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

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

And how do I perform summation of each element inside the list()? For example, my desired output is as below:

[[1]]
     [,1] [,2] [,3]
[1,]    3    9   15
[2,]    5   11   17
[3,]    7   13   19

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

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

I have tried using list(Reduce(`+`, x)) however it does not work.


回答1:


Since you want to keep top-level list use lapply :

lapply(x, function(l) if(is.list(l)) Reduce(`+`, l) else l)

#[[1]]
#     [,1] [,2] [,3]
#[1,]    3    9   15
#[2,]    5   11   17
#[3,]    7   13   19

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

#[[3]]
#     [,1] [,2] [,3]
#[1,]    4    7   10
#[2,]    5    8   11
#[3,]    6    9   12



回答2:


A corresponding purrr version of @RonakShah's answer with map_if():

library(purrr)

map_if(x, is.list, reduce, `+`)

# [[1]]
#      [,1] [,2] [,3]
# [1,]    3    9   15
# [2,]    5   11   17
# [3,]    7   13   19
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,]    3    6    9
# [2,]    4    7   10
# [3,]    5    8   11
# 
# [[3]]
#      [,1] [,2] [,3]
# [1,]    4    7   10
# [2,]    5    8   11
# [3,]    6    9   12


来源:https://stackoverflow.com/questions/63231431/sum-of-a-list-of-matrices-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!