Weighted rowSums of a matrix

房东的猫 提交于 2020-01-11 11:09:25

问题


I have a matrix like this:

I would like to sum every value of a single row but weighted.

Example: Given a specific row, the sum would be:

S = x1 * loan + x2 * mortdue + x3 * value + ...

x1, x2, x3, ... are predefined values.

I tried rowSums() and things like that but I have not been able to figure out how to do it properly.


回答1:


You are looking for a matrix-vector multiplication. For example, if you have a matrix:

set.seed(0)
A <- matrix(round(rnorm(9), 1), 3)
#     [,1] [,2] [,3]
#[1,]  1.3  1.3 -0.9
#[2,] -0.3  0.4 -0.3
#[3,]  1.3 -1.5  0.0

And you have another vector x, which is what you called "ponderation":

x <- round(rnorm(3), 1)
#[1]  2.4  0.8 -0.8

You can do

drop(A %*% x)
#[1]  4.88 -0.16  1.92

The drop just convert the result single column matrix into a 1D vector.

You can have a quick check to see this is what you want:

sum(A[1, ] * x)
#[1] 4.88

sum(A[2, ] * x)
#[1] -0.16

sum(A[3, ] * x)
#[1] 1.92

Compared with rowSums(), you can also think such computation as a "weighted rowSums".


At the moment, it seems more likely that you have a data frame rather than a matrix. You can convert this data frame to matrix by as.matrix().



来源:https://stackoverflow.com/questions/39837940/weighted-rowsums-of-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!