[R] Help in matrix

peter dalgaard pdalgd at gmail.com
Tue Mar 6 14:44:27 CET 2012


On Mar 6, 2012, at 13:02 , arunkumar1111 wrote:

> Hi
> 
> I have a matrix
> 
> a =  1 2 3
>        1 2 3
>         1 2 3
>          1 2 3
>          1 2 3
>          1 2 3
> 
> b = 5 6 7
>       8 9 10
> I want output as
> 
> c  =   5  2 3
>         8 2 3
>        1 6 3
>        1 9 3
>         1 2 7
>        1 2 10
> 
> 
> Please any on help to avoid reduncy of my code

Here's one way:

> a <- matrix(rep(1:3,each=6),6)
> a
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3
[5,]    1    2    3
[6,]    1    2    3
> b <- matrix(5:10,2,byrow=T)
> ix <- cbind(1:6,rep(1:3,each=2))
> a[ix] <- b
> a
     [,1] [,2] [,3]
[1,]    5    2    3
[2,]    8    2    3
[3,]    1    6    3
[4,]    1    9    3
[5,]    1    2    7
[6,]    1    2   10


-- 
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list