约束矩阵计算循环

Loop for constrained matrix calculation

我在R中有一个随机矩阵,即M1定义如下

M1<-matrix(1:20,nrow=4,ncol=5)

> M1
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

我想根据以下约束创建第二个。每行必须包含行总和减去前一点。每行的含义元素 (1,1) = 45、(1,2)=44、(1,3)=39 等。但我想在一个循环中进行,这样每次有人更改矩阵(及其维度)时,代码就能够计算出相应的矩阵。称为 M2 的最终矩阵必须是

的形式
> M2
     [,1] [,2] [,3] [,4] [,5]
[1,]   45   44   39   30   17
[2,]   50   48   42   32   18
[3,]   55   52   45   34   19
[4,]   60   56   48   36   20 

如何定义循环以便计算它?

matrixStats中有rowCumsums函数可以使用

library(matrixStats)
ind <- ncol(M1):1
rowCumsums(M1[, ind])[, ind]

-输出

     [,1] [,2] [,3] [,4] [,5]
[1,]   45   44   39   30   17
[2,]   50   48   42   32   18
[3,]   55   52   45   34   19
[4,]   60   56   48   36   20

或者可以使用 revcumsum 来自 spatstat.utils

library(spatstat.utils)
t(apply(M1, 1, revcumsum))

-输出

      [,1] [,2] [,3] [,4] [,5]
[1,]   45   44   39   30   17
[2,]   50   48   42   32   18
[3,]   55   52   45   34   19
[4,]   60   56   48   36   20

一些基础 R 选项

> rowSums(M1) - cbind(0, do.call(cbind, Reduce(`+`, as.data.frame(M1)[-ncol(M1)], accumulate = TRUE)))
     [,1] [,2] [,3] [,4] [,5]
[1,]   45   44   39   30   17
[2,]   50   48   42   32   18
[3,]   55   52   45   34   19
[4,]   60   56   48   36   20

> t(apply(M1, 1, function(v) sum(v) - head(cumsum(c(0, v)), -1)))
     [,1] [,2] [,3] [,4] [,5]
[1,]   45   44   39   30   17
[2,]   50   48   42   32   18
[3,]   55   52   45   34   19
[4,]   60   56   48   36   20