对矩阵中的每 N 个值求和 [英] Sum Every N Values in Matrix

查看:30
本文介绍了对矩阵中的每 N 个值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我查看了之前发布的这个问题,该问题用于对矩阵中每一行中的每 2 个值求和.链接在这里:对行中的特定列求和.我还在这里查看了另一个问题:R 对矩阵中的每 k 列求和 与我的更相似.在这种情况下,我无法使解决方案起作用.这是我正在使用的代码...

So I have taken a look at this question posted before which was used for summing every 2 values in each row in a matrix. Here is the link: sum specific columns among rows. I also took a look at another question here: R Sum every k columns in matrix which is more similiar to mine. I could not get the solution in this case to work. Here is the code that I am working with...

y <- matrix(1:27, nrow = 3)
y

m1 <- as.matrix(y)
n <- 3
dim(m1) <- c(nrow(m1)/n, ncol(m1), n)
res <- matrix(rowSums(apply(m1, 1, I)), ncol=n)
identical(res[1,],rowSums(y[1:3,]))


sapply(split.default(y, 0:(length(y)-1) %/% 3), rowSums)

我在应用此功能时收到一条错误消息.所需的输出是具有以下值的矩阵:

I just get an error message when applying this. The desired output is a matrix with the following values:

      [,1] [,2] [,3]
[1,]   12   39   66
[2,]   15   42   69
[3,]   18   45   72

推荐答案

要对每一行中 n 个元素的连续集合求和,您只需要编写一个进行求和的函数并将其应用于每行:

To sum consecutive sets of n elements from each row, you just need to write a function that does the summing and apply it to each row:

n <- 3
t(apply(y, 1, function(x) tapply(x, ceiling(seq_along(x)/n), sum)))
#       1  2  3
# [1,] 12 39 66
# [2,] 15 42 69
# [3,] 18 45 72

这篇关于对矩阵中的每 N 个值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆