[R] 3d matrix * 1d matrix question

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Oct 2 00:03:24 CEST 2004


gene <gene02_r at smalltime.com> writes:

> Apologies for the rather newbie question, but I haven't been able to
> figure this out.
> I've got a 3d matrix (though presumably, the answer would be the same
> as for a 2d matrix) which I want to multiply by the values in a vector
> like so:
> 
> matrix m is:
> 
> , , 1
>       [,1] [,2]
> [1,]    1    6
> [2,]    2    7
> [3,]    3    8
> 
> , , 2
>       [,1] [,2]
> [1,]   21   26
> [2,]   22   27
> [3,]   23   28
> 
> , , 3
>       [,1] [,2]
> [1,]   41   46
> [2,]   42   47
> [3,]   43   48
> 
> 
> vector v is c(2,10).
> 
> I want to multiply m by v along the columns to get this result:
> 
> , , 1
>       [,1] [,2]
> [1,]    2   60
> [2,]    4   70
> [3,]    6   80
> 
> , , 2
>       [,1] [,2]
> [1,]   42   260
> [2,]   44   270
> [3,]   46   280
> 
> , , 3
>       [,1] [,2]
> [1,]   82   460
> [2,]   84   470
> [3,]   86   480
> 
> 
> So, I figured I could do this by populating a new matrix the same
> dimensions as m with the values from v repeated in the right order and
> multiplying m by the new matrix.  It feels like there should be a
> one-step way to do this, though, especially since my real data is a
> very large data set and it would be memory-inefficient to create a new
> giant temporary matrix.

You don't need the full replicate matrix, only enough to allow
recycling to do its job. In this case, m * rep(c(2,10),each=3) should
do the trick. However, there's a function designed for the purpose:

  sweep(m, 2, v, "*")

(well, maybe "almost designed for"; takes a little thought to realize
that your problem is similar to sweeping out means along array extents.)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list