简体   繁体   English

R 中矩阵列表的总和

[英]Sum of a list of matrices in R

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:假设我有 4 个矩阵:

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:我想以这样的方式将它们放入list()中:

[[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() ?以及如何对list()中的每个元素进行求和? For example, my desired output is as below:例如,我想要的 output 如下:

[[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.我试过使用list(Reduce(`+`, x))但它不起作用。

Since you want to keep top-level list use lapply :由于您想保留顶级列表,因此请使用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

A corresponding purrr version of @RonakShah 's answer with map_if() : @RonakShah 对map_if map_if()的回答的相应purrr版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM