也許這很容易。我有一個矩陣: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
'testM [,seq(1,ncol(testM),by = 2)] + testM [,seq(2,ncol(testM),by = 2)]'與列的顯式索引相似。 – jogo