[R] Bind together two vectors of different length...

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jul 30 17:33:02 CEST 2007


Using the zoo package create zoo objects and merge them.  This
code assumes that A and B each have unique and ascending values:

> library(zoo)
> A <- seq(1, 10, 1)
> B <- seq(1, 10, 2)
> t(merge(A = zoo(A,A), B = zoo(B,B), fill = 0))
  1 2 3 4 5 6 7 8 9 10
A 1 2 3 4 5 6 7 8 9 10
B 1 0 3 0 5 0 7 0 9  0

Omit fill = 0 to fill with NAs (which is the default).  Note that if
we define A <- 1:10 (rather than as we did it above) then A will be
integer while B will be numeric so we will get a warning (which we
can eliminate with the suppressWarnings warnings) but it still
works.

A variation of this without zoo is:

> t(merge(cbind(A), cbind(B, B), by = 1, all.x = TRUE))
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
A    1    2    3    4    5    6    7    8    9    10
B    1   NA    3   NA    5   NA    7   NA    9    NA

however, R's merge does not support fill= so you will have
to replace the NAs with 0's yourself if you want those instead
of NA's.

> out <- t(merge(cbind(A), cbind(B, B), by = 1, all.x = TRUE))
> out[is.na(out)] <- 0  # replace NA's with 0
> out
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
A    1    2    3    4    5    6    7    8    9    10
B    1    0    3    0    5    0    7    0    9     0



On 7/30/07, Andris Jankevics <andza at osi.lv> wrote:
> Dear everyone,
>
> I've got difficulties in realizing the following
> task:
>
> I have two vectors:
> A <- c(1:10)
> B<- seq(1,10,2)
>
> Now I want to make a table form vectors A and B as rows, and if a value of A
> isn't present B, then I want to put a N/A symbol in it:
>
> Output should look like this:
>
> 1 2 3 4 5 6 7 8 9 10
> 1 0 3 0 5 0 7 0 9 0
>
> How can I do this in R?
>
> Thank you.
>
> --
> Andris Jankevics
> Assistant
> Department of Medicinal Chemistry
> Latvian Institute of Organic Synthesis
> Aizkraukles 21, LV-1006, Riga, Latvia
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>



More information about the R-help mailing list