[R] Multiply each column of array by vector component

Marc Schwartz marc_schwartz at comcast.net
Thu Nov 15 19:03:00 CET 2007


On Thu, 2007-11-15 at 17:50 +0000, M.T.Charemza at warwick.ac.uk wrote:
> Hi,
> 
> I've got an array, say with i,jth entry = A_ij, and a vector, say with jth
> entry= v_j. I would like to multiply each column of the array by the
> corresponding vector component, i,e. find the array with i,jth entry
> 
> A_ij * v_j
> 
> This seems so basic but I can't figure out how to do it without a loop.
> Any suggestions?
> 
> Michal.

If I understand you correctly:

  t(t(A) * v)


set.seed(1)

A <- matrix(sample(20), ncol = 2)
v <- c(5, 2)

> A
      [,1] [,2]
 [1,]    6    3
 [2,]    8    2
 [3,]   11   20
 [4,]   16   10
 [5,]    4    5
 [6,]   14    7
 [7,]   15   12
 [8,]    9   17
 [9,]   19   18
[10,]    1   13


> t(t(A) * v)
      [,1] [,2]
 [1,]   30    6
 [2,]   40    4
 [3,]   55   40
 [4,]   80   20
 [5,]   20   10
 [6,]   70   14
 [7,]   75   24
 [8,]   45   34
 [9,]   95   36
[10,]    5   26

HTH,

Marc Schwartz



More information about the R-help mailing list