本文介绍了R按行乘法-是否重设样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个(lot x 5)矩阵和(1 x 5)矩阵,是否有比这更好的方式将它们按行相乘:

If I have, say, an (lots x 5) matrix and a (1 x 5) matrix, is there a better way to multiply them row-wise than this:

> 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

这有效,但似乎很糟糕.我有缺少的功能吗?

This works but seems bad. Is there a function I'm missing?

推荐答案

另一个选项是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按行乘法-是否重设样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 20:17