R 中矩阵列表的总和 [英] Sum of a list of matrices in R
本文介绍了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:
假设我有 4 个矩阵:
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)
我想以这样的方式将它们放入 list()
中:
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
我如何对 list()
中的每个元素求和?例如,我想要的输出如下:
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
我尝试过使用 list(Reduce(`+`, x))
但是它不起作用.
I have tried using list(Reduce(`+`, x))
however it does not work.
推荐答案
既然要保留顶级列表,请使用 lapply
:
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
这篇关于R 中矩阵列表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文