【问题标题】:summing element of a row matrix to another matrix with their corresponding columns [duplicate]将行矩阵的元素与对应列的另一个矩阵相加[重复]
【发布时间】:2020-07-15 12:13:16
【问题描述】:

我想将矩阵 A 的每一行与矩阵 B 相加。具有预期结果的可重现示例:

set.seed(1)
A <- matrix(round(runif(15, 1, 15)), nrow = 3, ncol = 5)
B <- matrix(seq(100,500,100), nrow = 1, ncol = 5)

> A
     [,1] [,2] [,3] [,4] [,5]
[1,]    5   14   14    2   11
[2,]    6    4   10    4    6
[3,]    9   14   10    3   12

> B
     [,1] [,2] [,3] [,4] [,5]
[1,]  100  200  300  400  500

# Expected result
> C
     [,1] [,2] [,3] [,4] [,5]
[1,]  105  214  314  402  511
[2,]  106  204  310  404  506
[3,]  109  214  310  403  512

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    您可以使用sweep 来添加AB

    sweep(A, 2, B, "+")
    #    [,1] [,2] [,3] [,4] [,5]
    #[1,]  105  214  314  402  511
    #[2,]  106  204  310  404  506
    #[3,]  109  214  310  403  512
    

    你也可以使用col:

    A + B[col(A)]
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]  105  214  314  402  511
    #[2,]  106  204  310  404  506
    #[3,]  109  214  310  403  512
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多