Alejandro Jiménez Rico Alejandro Jiménez Rico - 2 months ago 18
R Question

Weighted rowSums of a matrix

I have a matrix like this:



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

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.

Answer

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().