-1

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]
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
AJ19
  • 83
  • 7
  • 1
    Please [include a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), and clearly state what you would expect as an output and what you get instead (e.g. any error appearing?) – nico Feb 08 '14 at 07:39
  • That's not R code. Create a small example with R code. – IRTFM Feb 08 '14 at 23:00

2 Answers2

0
m<-matrix(runif(100),ncol=5) #your matrix
r<-c(1:5)               #your vector
t(apply(m,1,function(x)x*r))
Troy
  • 8,581
  • 29
  • 32
0

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
Roland
  • 127,288
  • 10
  • 191
  • 288