【问题标题】:Calculations within a matrix with internal, references that are anchored to columns within the matrix in R具有内部引用的矩阵内的计算锚定到 R 中矩阵内的列
【发布时间】:2020-12-09 18:49:25
【问题描述】:

我有一个矩阵,我想对矩阵中的每个数字执行计算,以便我得到另一个具有相同维度的矩阵,仅计算结果。这应该很容易,只是方程式的一部分取决于我访问的列,因为我需要对该列中第 [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,])))

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

我在想,也许我可以只修改上述计算中的函数以使其工作,或者编写一些迭代矩阵的每一列的东西,但我不确定如何以某种方式做到这一点这给了我想要的输出矩阵。

任何帮助将不胜感激。

【问题讨论】:

    标签: r matrix calculated-columns


    【解决方案1】:

    我认为这应该适合你:

    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
    

    【讨论】:

    • 这非常有效!非常感谢!
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      相关资源
      最近更新 更多