Search code examples
rdataframeapplyweighted-average

Data frame/matrix row times vector/list element wise


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


Solution

  • 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.