Interleave lists in R -


let's have 2 lists in r, not of equal length, like:

 <- list('a.1','a.2', 'a.3')  b <- list('b.1','b.2', 'b.3', 'b.4') 

what best way construct list of interleaved elements where, once element of shorter list had been added, remaining elements of longer list append @ end?, like:

interleaved <- list('a.1','b.1','a.2', 'b.2', 'a.3', 'b.3','b.4') 

without using loop. know mapply works case both lists have equal length.

here's 1 way:

idx <- order(c(seq_along(a), seq_along(b))) unlist(c(a,b))[idx]  # [1] "a.1" "b.1" "a.2" "b.2" "a.3" "b.3" "b.4" 

as @james points out, since need list back, should do:

(c(a,b))[idx] 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -