This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R programming question: insert alternately

Hi Guys,

I have a quick question:

I have list of characters in two different objects

object1

 "1.TY"   "2.TY"   "4.TY"   "5.TY"

object2

"1.MN"   "2.MN"   "4.MN"   "5.MN"

I want to merge them alternating one after other, as shown below.

Result

"1.TY"  "1.MN"  "2.TY" "2.MN"  "4.TY" "4.MN"  "5.TY"  "5.MN"

Thank you for your help.

r

4 answers

For anyone else interested in the different performance of these solutions, I did a crude comparison.

The TLDR would be: the "grow a for loop" approach works for short vectors, but scales terribly. The rbind method, as unintuitive as it might be, is the fastest of the lot

a <- c("1.TY","2.TY","4.TY","5.TY")
b <- c("1.MN","2.MN","4.MN","5.MN")
results <- c()
for (i in 1:4){
  results <- c(results, a[i], b[i])
}
> results
[1] "1.TY" "1.MN" "2.TY" "2.MN" "4.TY" "4.MN" "5.TY" "5.MN"

Enjoy :)

This should get the job done, and for shorter vectors won't take too long. But be aware, starting an empty vector and growing it like this, though sensible in many languages, is usually very slow in r. I've not tested it, but as.character(rbind(a,b)) should work, and starting a vector of the final size and filling it by index (using seq() ) would likely be faster.

Thank you, got what I need.

This solution might be preferable in R as it should be orders of magnitude faster than a for-loop (although in practice it might not matter):

a <- c("1.TY","2.TY","4.TY","5.TY", "0.TY")
b <- c("1.MN","2.MN","4.MN","5.MN", "0.MN")
ord<- order(c(1:length(a), 1:length(b)))
results<- c(a, b)[ord]
> results
 [1] "1.TY" "1.MN" "2.TY" "2.MN" "4.TY" "4.MN" "5.TY" "5.MN" "0.TY" "0.MN"
Use the interleave-function from ggplot2-package

Log in to answer this question.