basic R question: concatenate two numeric vectors grouped by element index
2
0
Entering edit mode
Johannes Rainer ★ 2.1k
@johannes-rainer-6987
Last seen 5 weeks ago
Italy

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.

 

thanks in advance!

jo

 

 

 

basic R • 3.8k views
ADD COMMENT
1
Entering edit mode
@herve-pages-1542
Last seen 3 days ago
Seattle, WA, United States

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.

ADD COMMENT
3
Entering edit mode
Axel Klenk ★ 1.0k
@axel-klenk-3224
Last seen 5 hours ago
UPF, Barcelona, Spain

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

ADD COMMENT
0
Entering edit mode

Awesome! About 4x faster than my C1 method! 

ADD REPLY

Login before adding your answer.

Traffic: 437 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6