m<-matrix(runif(100),ncol=5) #your matrix
r<-c(1:5) #your vector
t(apply(m,1,function(x)x*r))
How to multiply a column by vector components? [closed]
-
08-10-2022 - |
Question
I have a 5 column matrix which I am multiplying by a 5 row vector. Each column should be multiplied by the corresponding element in the vector. I have the information in both data.frame and matrix form - was unsure if it mattered to do matrix operators.
This is the final few minutes of spending at least 6 hours on this today, so I hope the example makes sense. Please excuse the simplicity of the problem, I just cannot think right now and am running short on time.
Ex.
Column 1 has 252 rows. Vector = [a,b,c,d,e]. Column 1[1:252] %*% Vector[a] Column 2 has 252 rows. Column 2[1:252] %*% Vector [b] Column 4 has 194 rows of "NA" or "0". #I don't know if this changes anything, but thought it useful info. Column 4[1:252] %*% Vector[d]
Solution
OTHER TIPS
This should be faster than apply
. It relies on vector recycling.
m<-matrix(rep(1,10),ncol=5)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 1 1 1 1
#[2,] 1 1 1 1 1
r<-c(1:5)
t(t(m)*r)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 1 2 3 4 5
#[2,] 1 2 3 4 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow