R programming question: insert alternately
4
0
Entering edit mode
9.6 years ago
MAPK ★ 2.1k

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 • 2.6k views
ADD COMMENT
4
Entering edit mode
9.6 years ago
David W 4.9k

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

ADD COMMENT
1
Entering edit mode
9.6 years ago
TriS ★ 4.7k
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 :)

ADD COMMENT
1
Entering edit mode
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.
ADD REPLY
0
Entering edit mode

Thank you, got what I need.

ADD REPLY
1
Entering edit mode
9.6 years ago

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"
ADD COMMENT
0
Entering edit mode
9.6 years ago
Irsan ★ 7.8k
Use the interleave-function from ggplot2-package
ADD COMMENT

Login before adding your answer.

Traffic: 1571 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