1

I have a matrix that looks like this

raw<- c(1,2,3,4,5,6,7,8,9)
mat<- matrix(raw,ncol = 3, nrow = 3)

to get me

      [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

Plus a vector or list

vector<-c(1,2,3)

What I need to do is to multiply each row by the corresponding vector entry i.e 1*1 , 4*2, 7* 3 etc.

My final goal is to calculate a weighted average of row and vector.

I tried using

apply(c(mat,vector),1,prod)

I would like to know if it can be done in an elegant way at once or how I can calculate the row*vector product correctly.

thanks

slamballais
  • 3,161
  • 3
  • 18
  • 29
ThatQuantDude
  • 759
  • 1
  • 9
  • 26

2 Answers2

3

We can use sweep to apply the product function over the columns of mat:

sweep(mat, 2, vector, '*')
#     [,1] [,2] [,3]
#[1,]    1    8   21
#[2,]    2   10   24
#[3,]    3   12   27
Pierre L
  • 28,203
  • 6
  • 47
  • 69
2

If you want only the operation in your question you can do

mat * rep(vector, each=3)  # or
mat * rep(vector, each=nrow(mat))  # or
mat * matrix(vector, nrow(mat), ncol(mat), byrow=TRUE)

In the comments I read you want to calculate the rowwise mean for the resulting matrix. So you can do:

rowMeans(mat*rep(vector, each=nrow(mat))) # or:
apply(mat, 1, weighted.mean, w=vector)*mean(vector) # both steps together

Normally the function rowMeans() is faster than alternative calculations.

jogo
  • 12,469
  • 11
  • 37
  • 42