[R] rearrange data columns
(Ted Harding)
Ted.Harding at manchester.ac.uk
Thu Oct 11 14:46:10 CEST 2007
On 11-Oct-07 12:09:19, Robin Hankin wrote:
>
> On 11 Oct 2007, at 12:55, Martin Ivanov wrote:
>
>> Dear R users,
>> I need to to the the following. Let a= 1 2 3
>> 4 5 6
>> and b= -1 -2 -3 be (2x3) matrices.
>> -4 -5 -6
>> I need to combine the two matrices into a new (2x6) matrix like this:
>>
>> ab = ( 1 -1 2 -2 3 -3 )
>> 4 -4 5 -5 6 -6
>>
>> How can this be done in R?
>
> > a
> [,1] [,2] [,3]
> [1,] 1 2 3
> [2,] 4 5 6
> > b
> [,1] [,2] [,3]
> [1,] -1 -2 -3
> [2,] -4 -5 -6
>
> > x <- cbind(a,b)+NA
> > x
> [,1] [,2] [,3] [,4] [,5] [,6]
> [1,] NA NA NA NA NA NA
> [2,] NA NA NA NA NA NA
> > x[,seq(from=1,by=2,len=3)] <- a
> > x[,seq(from=2,by=2,len=3)] <- b
> > x
> [,1] [,2] [,3] [,4] [,5] [,6]
> [1,] 1 -1 2 -2 3 -3
> [2,] 4 -4 5 -5 6 -6
> >
>
>
> HTH
>
> rksh
What's wrong with
a
## [,1] [,2] [,3]
##[1,] 1 2 3
##[2,] 4 5 6
b
## [,1] [,2] [,3]
##[1,] -1 -2 -3
##[2,] -4 -5 -6
cbind(a,b)[,c(1,4,2,5,3,6)]
## [,1] [,2] [,3] [,4] [,5] [,6]
##[1,] 1 -1 2 -2 3 -3
##[2,] 4 -4 5 -5 6 -6
??
Of course, for a more general case, you'd need a method for
generating the appropriate version of c(1,4,2,5,3,6) -- e.g.
something like Robin's "seq".
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 11-Oct-07 Time: 13:46:06
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list