可能这很容易。我有一个矩阵:

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[,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

10-04 23:21