Rainer M Krug
2007-Oct-23 15:03 UTC
[R] "adding" matrix of smaller dimensions to matrix of larger dimensions and "apply" question
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
Henrique Dallazuanna
2007-Oct-23 15:35 UTC
[R] "adding" matrix of smaller dimensions to matrix of larger dimensions and "apply" question
Perhaps: b[1:nrow(d), 2:3] <- b[1:nrow(d), 2:3]+d For seconde questin you can use the which function. which(b==5, arr.ind=T) On 23/10/2007, Rainer M Krug <Rainer+R-help@krugs.de> wrote:> > 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 > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]