如何将每个维度中的数组值求和成一个矩阵 [英] How to sum values of array in each dimension into one matrix
问题描述
我有一个具有三个维度的数组,想对每个维度的值求和,最后得到一个数据矩阵.
I've one array with three dimensions and want to sum up the values in each dimension and end up with one data matrix.
这里是一个例子:
array1 <- array(c(-5.5,6,3),dim = c(3,4,3))
matrix <- matrix(NA, nrow=3, ncol=4)
matrix
[,1] [,2] [,3] [,4]
[1,] -16.5 -16.5 -16.5 -16.5
[2,] 18 18 18 18
[3,] 9 9 9 9
是否可以通过循环而不是使用任何套用功能来做到这一点?
Is it possible to do it somehow with a loop instead of using any apply function?
提前谢谢!
推荐答案
您确定要对每个维度求和吗?您的示例显示了第三维的求和.
Are you sure that you want to sum along each dimension? Your example shows summation along the third dimension.
无论如何,这是可以完成的操作(您已明确表示不想使用apply
):
Anyway, this is how it could be done (you made it explicit that you didn't want to use apply
):
X <- array(c(-5.5,6,3), dim = c(3,4,3))
rows <- dim(X)[1]
cols <- dim(X)[2]
result <- matrix(0, nrow=rows, ncol=cols)
for (i in seq(rows)) {
for (j in seq(cols)) {
result[i,j] <- sum(X[i,j,])
}
}
给你
> result
[,1] [,2] [,3] [,4]
[1,] -16.5 -16.5 -16.5 -16.5
[2,] 18.0 18.0 18.0 18.0
[3,] 9.0 9.0 9.0 9.0
编辑:自您提出问题以来(但我建议您不要使用此解决方案,因为它很慢,而且在R中肯定不是惯用的方式):
Since you asked (but I would advise against this solution as it is slow and certainly not the idiomatic way to do all this in R):
result <- matrix(0, nrow=rows, ncol=cols)
for (i in seq(rows)) {
for (j in seq(cols)) {
for (k in seq(dim(X)[3])) {
result[i,j] <- result[i,j] + X[i,j,k]
}
}
}
请注意,result
已用零初始化.如果不是这种情况,则必须在j
和k
循环之间对其进行初始化.
Note that result
has been initialized with zeroes. If that weren't the case, you'd have to initialize it between the j
and k
loops.
这篇关于如何将每个维度中的数组值求和成一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!