矩阵内的计算,内部引用锚定到 R 中矩阵内的列

Calculations within a matrix with internal, references that are anchored to columns within the matrix in R

我有一个矩阵,我想对矩阵中的每个数字进行计算,以便只用计算结果得到另一个具有相同维度的矩阵。这应该很容易,只是等式的一部分取决于我正在访问的列,因为我需要对该列内第 [3,] 行的数字进行内部引用。

我想应用的等式是: output matrix value = input_matrix value at a given position + (1- (matrix value at [3,] and in the same column as the input matrix value))

例如,对于矩阵中的 (1,1),计算结果为 1+(1-3)

对于矩阵中的位置 (1,2),计算结果为 5+(1-7)

input_matrix<- matrix(1:12, nrow = 4, ncol = 3)

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

输出矩阵最终应如下所示:

     [,1] [,2] [,3]
[1,]    -1   -1  -1
[2,]    0    0   0
[3,]    1    1   1
[4,]    2    2   2

我试过这样做:

output_matrix<-apply(input_matrix,c(1,2), function(x) x+(1-(input_matrix[3,])))

但这给了我三个维度错误的矩阵作为输出。

我在想,也许我可以修改上面计算中的函数来让它工作,或者写一些东西来遍历矩阵的每一列,但我不确定如何在一种给我想要的输出矩阵的方法。

如有任何帮助,我们将不胜感激。

我认为这对你有用:

apply(input_matrix, margin = 2, function(x) x + (1 - x[3]))
     [,1] [,2] [,3]
[1,]   -1   -1   -1
[2,]    0    0    0
[3,]    1    1    1
[4,]    2    2    2

我们也可以用矢量化的方式做到这一点

input_matrix + (1 - input_matrix[3,][col(input_matrix)])
#     [,1] [,2] [,3]
#[1,]   -1   -1   -1
#[2,]    0    0    0
#[3,]    1    1    1
#[4,]    2    2    2