R: How to sum pairs in a Matrix by row?
Probably this would be easy. I have a Matrix: 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 and I want to "reduce" the matrix summing column pairs by row. Expected result: [,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 I tried this but doesn't work X <- apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x+1]) ) Error in apply