2016-04-05 99 views
2

也許這很容易。我有一個矩陣:R:如何按行排列矩陣中的對?

testM <- matrix(1:40, ncol = 4, byrow = FALSE) 
testM 
     [,1] [,2] [,3] [,4] 
[1,] 1 11 21 31 
[2,] 2 12 22 32 
[3,] 3 13 23 33 
[4,] 4 14 24 34 
[5,] 5 15 25 35 
[6,] 6 16 26 36 
[7,] 7 17 27 37 
[8,] 8 18 28 38 
[9,] 9 19 29 39 
[10,] 10 20 30 40 

我想「減少」行矩陣求和列對。預期結果:

 [,1] [,2] 
[1,] 12 52 
[2,] 14 54 
[3,] 16 56 
[4,] 18 58 
[5,] 20 60 
[6,] 22 62 
[7,] 24 64 
[8,] 26 66 
[9,] 28 68 
[10,] 30 70 

我試過,但不起作用

X <- apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x+1])) 

Error in apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x + : 
    dim(X) must have a positive length 

回答

6
testM[,c(T,F)]+testM[,c(F,T)]; 
##  [,1] [,2] 
## [1,] 12 52 
## [2,] 14 54 
## [3,] 16 56 
## [4,] 18 58 
## [5,] 20 60 
## [6,] 22 62 
## [7,] 24 64 
## [8,] 26 66 
## [9,] 28 68 
## [10,] 30 70 
+1

'testM [,seq(1,ncol(testM),by = 2)] + testM [,seq(2,ncol(testM),by = 2)]'與列的顯式索引相似。 – jogo

0

如何:

matrix(c(testM[, 1] + testM[, 2], testM[, 2] + testM[, 4]), nrow = 10) 
+0

'testM [,c(1,3)] + testM [,c(2,4)]'是相同的。 – jogo

0

在你最初的想法的解決方案:

sapply(seq(2, ncol(testM), 2), function(x) apply(testM[, (x-1):x], 1, sum)) 
3

下面是使用rowSums()

sapply(list(1:2,3:4) , function(i) rowSums(testM[,i])) 

如果列數應該是任意一個解決方案,它變得更加複雜:

li <- split(1:ncol(testM) , rep(1:(ncol(testM)/2), times=1 , each=2)) 

sapply(li , function(i) rowSums(testM[,i])) 
+1

@Frank:是的,我爲這種情況添加了一個解決方案。 –

+0

'rowsum'給出另一個(通常是快速的)替代方案。't(rowsum(t(testM),rep(1:2,each = 2)))',其中第二個('group')參數可以用於任意列進行求和。 – user20650

1

我們可以做一個矩陣乘法:

M <- matrix(c(1,1,0,0, 0,0,1,1), 4, 2) 
testM %*% M 

另一與tapply()解決方案:

g <- gl(ncol(testM)/2, 2) 
t(apply(testM, 1, FUN=tapply, INDEX=g, sum))