Search
Question: basic R question: concatenate two numeric vectors grouped by element index
0
3.8 years ago by
Johannes Rainer1.3k
Italy
Johannes Rainer1.3k wrote:

dear all!

So basically what I have are two numerical vectors:

A <- c( 1, 2, 3, 4, 6, 7 )

B <- c( 8, 9, 10, 11, 12, 13 )

and I would like to combine them so that the result would be:

1, 8, 2, 9, 3, 10, 4, 11, 6, 12, 7, 13

i.e. that the first element of B is next to the first of A and so on.

One way to do that is using paste, but that's really not nice coding...

as.numeric( unlist( strsplit( paste( A, B, sep=":" ), split=":" ) ) )

[1]  1  8  2  9  3 10  4 11  6 12  7 13

is there any other, better way to achieve the same.

jo

modified 3.8 years ago by Axel Klenk920 • written 3.8 years ago by Johannes Rainer1.3k
1
3.8 years ago by
Hervé Pagès ♦♦ 13k
United States
Hervé Pagès ♦♦ 13k wrote:

Hi jo,

You could either do:

C1 <- integer(2*length(A))
idx <- 2L * seq_along(A)
C1[idx] <- B
C1[idx - 1L] <- A

or, using a little hidden utility from S4Vectors:

C2 <- c(A, B)[S4Vectors:::make_XYZxyz_to_XxYyZz_subscript(length(A))]
identical(C1, C2)  # TRUE

but the first method is about twice faster.

H.

3
3.8 years ago by
Axel Klenk920
Switzerland
Axel Klenk920 wrote:

Hi jo,

just to add one: I usually do

as.vector(rbind(A, B))

which obviously requires A and B to be of the same length.

Cheers,

- axel