R 中矩阵列表的总和

问题描述 投票:0回答:3

我试图将矩阵列表放在一个列表中,然后在每个列表中求和。以下是代码的简单示例:

假设我有 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)

我想以这样的方式将它们放入

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

如何对

list()
内的每个元素进行求和? 例如,我想要的输出如下:

[[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))
但是它不起作用。

r list matrix sum
3个回答
2
投票

既然你想保留顶级列表,请使用

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

1
投票

对应的

purrr
版本的@RonakShah的答案与
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

0
投票

对我来说,使用

array
更优雅。这是一些示例代码。该示例计算平均值而不是总和。

R <- list(matrices, all of the same dimension)
# Combine all these into an array with an extra dimension
# corresponding to the different matrices
dn <- dimnames(R[[1]])   # fetch row and column names
rn <- dn[[1]]; cn <- dn[[2]]
A <- array(unlist(R), dim=c(length(rn), length(cn), length(R)),
           dimnames=list(rn, cn, NULL))
# Compute mean (separately for each metrix cell) 
# over matrices, ignoring NAs
Rmean <- apply(R, 1:2, mean, na.rm=TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.