[R] Simple... but...

(Ted Harding) Ted.Harding at manchester.ac.uk
Wed Jul 23 15:30:34 CEST 2008

On 23-Jul-08 12:54:49, Shubha Vishwanath Karanth wrote:
> Hi R,
> If 
> x=c(1,3,5)
> y=c(2,4,6)
> I need a vector which is c(1,2,3,4,5,6) from x and y.
> How do I do it? I mean the best way....
> Thanks, Shubha

Your query is ambiguous, in that it is not clear whether you want
a) The elements of the combination of x and y to be in increasing
   order, regardless of how they are distributed between x and y

   In which case a simple solution is sort(c(x,y))

b) The elements to be taken alternately from x and y, regardless
   of their values

   In which case a simple solution is as.vector(rbind(x,y))


  x <- c(1.1,1.2,1.3)
  y <- c(2.1,2.2,2.3)

  ## (a):
  # [1] 1.1 1.2 1.3 2.1 2.2 2.3

  ## (b)
  # [1] 1.1 2.1 1.2 2.2 1.3 2.3

The key to solution (b) is that R reads a matrix down the columns,
and rbind(x,y) puts x as a row above y as a row, so reading down
the columns alternates between x and y.

Hoping this helps,

E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 23-Jul-08                                       Time: 14:30:31
------------------------------ XFMail ------------------------------

More information about the R-help mailing list