26

I have following problem:

myvec <- c(1:3)

mymat <- as.matrix(cbind(a = 6:15, b = 16:25, c= 26:35))
mymat
       a  b  c
 [1,]  6 16 26
 [2,]  7 17 27
 [3,]  8 18 28
 [4,]  9 19 29
 [5,] 10 20 30
 [6,] 11 21 31
 [7,] 12 22 32
 [8,] 13 23 33
 [9,] 14 24 34
[10,] 15 25 35

I want to multiply the mymat with myvec and construct new vector such that

sum(6*1, 16*2, 26*3) 
sum(7*1, 17*2, 27*3)

....................
sum(15*1, 25*2, 35*3)

Sorry, this is simple question that I do not know...

Edit: typo corrected

jon
  • 11,186
  • 19
  • 80
  • 132

3 Answers3

55

The %*% operator in R does matrix multiplication:

> mymat %*% myvec
      [,1]
 [1,]  116
 [2,]  122
 ...
[10,]  170
Owen
  • 38,836
  • 14
  • 95
  • 125
2

An alternative, but longer way can be this one:

rowSums(t(apply(mymat, 1, function(x) myvec*x)),na.rm=T)

Is the only way that I found that can ignore NA's inside the matrix.

Liliana Pacheco
  • 881
  • 10
  • 13
1

Matrices are vectors in column major order:

 colSums(  t(mymat) * myvec )  

(Edited after hopefully reading question correctly this time.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Why the c( ) around the entire expression? – thelatemail Nov 08 '11 at 06:04
  • Maybe not needed? The idea was so it ends up as a vector. But that idea seems excessively cautious. I'll drop it. – IRTFM Nov 08 '11 at 06:28
  • If the matrix is stored in column major order, then you need to transpose it first before applying a row-wise multiplication. `colSums(t(mymat) * myvec)` – Calimo Oct 07 '13 at 14:48