# matrix multiplication in R to generated a weighted sum

Hi,

I am trying to do a weighted sum of a bunch of columns.
I have a weightings vector where each weight correspondence to a question in mydf.
I am having slight problems. I was wondering if anyone could nudge me in the right direction

Thanks

library(tibble)

weights <- c(0.0123, 0.1, 0.56)
mydf <- tibble(id = seq(1:50),
x = runif(50, 1, 99),
y = runif(50, 1, 99),
z = runif(50, 1, 99)) %>%
column_to_rownames('id')

weights %*% mydf



Hello,

what you want to do is a weighted sum, so basically matrix algebra. To multiply a vector with a matrix, you basically need two things:

1. A vector and a matrix

2. Comfortable dimensions for matrix multiplication.

With this in mind, you can have a look at the dimensions of your vector weights. It is a 3 \times 1 "matrix". On the other hand, your matrix has three columns and 50 rows, so it is a 50 \times 3 matrix. To obtain a meaningful result, you have to first coerce your data.frame into an actual matrix with as.matrix() (or, if you have a lot of data and need faster conversion, use collapse::qM()) and second arrange them in the right way:

library(tibble)

weights <- c(0.0123, 0.1, 0.56)
mydf <- tibble(id = seq(1:50),
x = runif(50, 1, 99),
y = runif(50, 1, 99),
z = runif(50, 1, 99)) %>%
column_to_rownames('id')

as.matrix(mydf)  %*% weights
#>         [,1]
#> 1  61.335315
#> 2  23.944288
#> 3   3.594572
#> 4  53.801873
#> 5  32.966212
#> 6  54.073599
#> 7  33.329541
#> 8  12.251728
#> 9  28.662665
#> 10 54.602872
#> 11 29.865924
#> 12 46.941808
#> 13 37.728464
#> 14 65.148778
#> 15 50.308076
#> 16 38.164087
#> 17 39.589346
#> 18 47.968581
#> 19 13.301430
#> 20 53.684308
#> 21 58.576841
#> 22  9.338697
#> 23 43.612830
#> 24 32.652218
#> 25 27.932359
#> 26 55.796967
#> 27 39.641971
#> 28 46.618407
#> 29 34.821906
#> 30 34.444772
#> 31 53.108446
#> 32 59.230032
#> 33 14.456050
#> 34 27.500888
#> 35 30.771397
#> 36  9.790532
#> 37 48.771767
#> 38 43.995186
#> 39 18.112868
#> 40  6.974020
#> 41 19.750707
#> 42 29.385625
#> 43 55.444336
#> 44 42.161868
#> 45 61.309429
#> 46 49.282377
#> 47 27.346332
#> 48 59.945529
#> 49 26.759811
#> 50 29.242717


Created on 2022-10-10 by the reprex package (v2.0.1)

The result is a 50 \times 1 vector with the weighted sums.

Kind regards

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.