Question: R programming question: insert alternately
0
gravatar for MAPK
4.2 years ago by
MAPK1.4k
United States
MAPK1.4k wrote:

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 • 1.4k views
ADD COMMENTlink modified 4.2 years ago • written 4.2 years ago by MAPK1.4k
4
gravatar for David W
4.2 years ago by
David W4.7k
New Zealand
David W4.7k wrote:

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 COMMENTlink written 4.2 years ago by David W4.7k
1
gravatar for TriS
4.2 years ago by
TriS3.8k
United States, Buffalo
TriS3.8k wrote:
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 COMMENTlink written 4.2 years ago by TriS3.8k
1
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 REPLYlink written 4.2 years ago by David W4.7k

Thank you, got what I need.

ADD REPLYlink written 4.2 years ago by MAPK1.4k
1
gravatar for dariober
4.2 years ago by
dariober10k
WCIP | Glasgow | UK
dariober10k wrote:

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 COMMENTlink modified 4.2 years ago • written 4.2 years ago by dariober10k
0
gravatar for Irsan
4.2 years ago by
Irsan6.9k
Amsterdam
Irsan6.9k wrote:
Use the interleave-function from ggplot2-package
ADD COMMENTlink written 4.2 years ago by Irsan6.9k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 964 users visited in the last hour