R对矩阵中的每k列求和 [英] R Sum every k columns in matrix

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

问题描述

我有一个矩阵temp1(尺寸为Nx16)(通常为NxM)

I have a matrix temp1 (dimensions Nx16) (generally, NxM)

我想将每一行中的每k列求和为一个值.

I would like to sum every k columns in each row to one value.

这是我到目前为止所要做的:

Here is what I got to so far:

cbind(rowSums(temp1[,c(1:4)]), rowSums(temp1[,c(5:8)]), rowSums(temp1[,c(9:12)]), rowSums(temp1[,c(13:16)]))

必须有一个更优雅(更通用)的方法来做到这一点.

There must be a more elegant (and generalized) method to do it.

我在这里注意到了类似的问题:
对行中的特定列求和

I have noticed similar question here:
sum specific columns among rows

无法使其与Ananda的解决方案配合使用; 出现以下错误:

couldn't make it work with Ananda's solution; Got following error:

sapply(split.default(temp1,0:(length(temp1)-1)%/%4),rowSums)

FUN(X [[1L]],...)错误:
"x"必须是至少二维的数组

sapply(split.default(temp1, 0:(length(temp1)-1) %/% 4), rowSums)

Error in FUN(X[[1L]], ...) :
'x' must be an array of at least two dimensions

请告知.

推荐答案

如果子矩阵的尺寸相等,则可以将尺寸更改为array,然后执行rowSums

If the dimensions are equal for the sub matrices, you could change the dimensions to an array and then do the rowSums

 m1 <- as.matrix(temp1)
 n <- 4
 dim(m1) <- c(nrow(m1), ncol(m1)/n, n)
 res <- matrix(rowSums(apply(m1, 2, I)), ncol=n)
 identical(res[,1],rowSums(temp1[,1:4]))
 #[1] TRUE

或者尺寸不相等

  t(sapply(seq(1,ncol(temp2), by=4), function(i) {
                  indx <- i:(i+3)
               rowSums(temp2[indx[indx <= ncol(temp2)]])}))

数据

set.seed(24)
temp1 <- as.data.frame(matrix(sample(1:20, 16*4, replace=TRUE), ncol=16))

set.seed(35)
temp2 <- as.data.frame(matrix(sample(1:20, 17*4, replace=TRUE), ncol=17))

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

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