[R] "adding" matrix of smaller dimensions to matrix of larger dimensions and "apply" question

Rainer M Krug Rainer+R-help at krugs.de
Tue Oct 23 17:03:58 CEST 2007


Hi

I have another question concerning matrices:
I have two matrices:

 > b <- matrix(1:25,5,5,byrow=T)
 > b
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    6    7    8    9   10
[3,]   11   12   13   14   15
[4,]   16   17   18   19   20
[5,]   21   22   23   24   25

and

 > d <- matrix(1:4,2,2,byrow=T)
 > d
      [,1] [,2]
[1,]    1    2
[2,]    3    4
 >


and I want to "add" d to b in such a way that I specify one cell in 
matrix b , e.g. [1,2]:


    [,1] [,2] [,3]   [,4]   [,5]
[1,]    1    2+1    3+2    4    5
[2,]    6    7+3    8+4    9   10
[3,]   11   12     13     14   15
[4,]   16   17     18     19   20
[5,]   21   22     23     24   25

Is there an easy way of doing this, apart from iterating through the 
matrix d?

Also, when I use

 > apply(d, c(1,2), function(x) {})

is there a way of knowing the column anr row which the element x is 
from, or o I have to use for loops for that?

Thanks in advance,

Rainer



More information about the R-help mailing list