gpt4 book ai didi

r - 使用 R 在矩阵上求和

转载 作者:行者123 更新时间:2023-12-04 11:42:49 27 4
gpt4 key购买 nike

我想制作一个多个矩阵的 cumsum 获取步骤。如果我们考虑:

A <- structure(c(1, 2, 3, 2, 3, 1, 4, 1, 2), .Dim = c(3, 3))
# [,1] [,2] [,3]
# [1,] 1 2 4
# [2,] 2 3 1
# [3,] 3 1 2
B <- structure(c(6, 1, 9, 6, 3, 7, 3, 2, 8), .Dim = c(3, 3))
# [,1] [,2] [,3]
# [1,] 6 6 3
# [2,] 1 3 2
# [3,] 9 7 8
C <- structure(c(1, 1, 2, 5, 3, 3, 3, 9, 1), .Dim = c(3, 3))
# [,1] [,2] [,3]
# [1,] 1 5 3
# [2,] 1 3 9
# [3,] 2 3 1

我想要以下结果:

     [,1] [,2] [,3]
[1,] 1 2 4
[2,] 2 3 1
[3,] 3 1 2

[,1] [,2] [,3]
[1,] 7 8 7
[2,] 3 6 3
[3,] 12 8 10

[,1] [,2] [,3]
[1,] 8 13 10
[2,] 4 9 12
[3,] 14 11 11

所有步骤!我可以用 for 循环来做到这一点,但是对于大矩阵来说它很慢,我该如何用 apply 来做到这一点?

最佳答案

对于 Reduce 来说,这是一项完美的工作:

Reduce("+", list(A,B,C), accumulate=TRUE)
[[1]]
[,1] [,2] [,3]
[1,] 1 2 4
[2,] 2 3 1
[3,] 3 1 2

[[2]]
[,1] [,2] [,3]
[1,] 7 8 7
[2,] 3 6 3
[3,] 12 8 10

[[3]]
[,1] [,2] [,3]
[1,] 8 13 10
[2,] 4 9 12
[3,] 14 11 11

关于r - 使用 R 在矩阵上求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836111/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com