This question already has answers here:
Multiply rows of matrix by vector?

(6 个回答)


6年前关闭。




如果我有一个 (lots x 5) 矩阵和一个 (1 x 5) 矩阵,有没有比这更好的方法将它们逐行相乘:
> q
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5

> z
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25

> t(apply(z,1,function (x) {x*q}))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   12   33   64  105
[2,]    2   14   36   68  110
[3,]    3   16   39   72  115
[4,]    4   18   42   76  120
[5,]    5   20   45   80  125

这有效,但似乎很糟糕。是否有我缺少的功能?

最佳答案

另一种选择是 sweep

sweep(z, 2, q, "*")
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1   12   33   64  105
# [2,]    2   14   36   68  110
# [3,]    3   16   39   72  115
# [4,]    4   18   42   76  120
# [5,]    5   20   45   80  125

关于R逐行乘法 - 重新设计?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27644220/

10-12 23:31