Let's say that I have two lists in R, not necessarily of equal length, like:
a <- list('a.1','a.2', 'a.3')
b <- list('b.1','b.2', 'b.3', 'b.4')
What is the best way to construct a list of interleaved elements where, once the element of the shorter list had been added, the remaining elements of the longer list are append at the end?, like:
interleaved <- list('a.1','b.1','a.2', 'b.2', 'a.3', 'b.3','b.4')
without using a loop. I know that mapply works for the case where both lists have equal length.
Here's one way:
As @James points out, since you need a list back, you should do:
While investigating a similar question, I came across this beautiful solution by Gabor Grothendieck (i.e. @GGrothendieck?) for certain cases:
This works equally well when
a
andb
are both lists, or whena
andb
are both vectors. It's not a precise solution to OP's question, because whena
andb
have different lengths, it will recycle the elements of the shorter sequence, printing a warning. However, since this solution is simple and elegant, and provides an answer to a very similar question--a question of some people (like me) who find their way to this page as a result--it seemed worth adding as an answer.Here's one option using the
interleave
function from ggplot2. I'm sure this can be improved upon, but it's a start:In particular, this will do weird things if the lists are actually the same length. Perhaps someone will chime in with a better way to do the indexing for
v[[2]]
in the last line that avoids that degenerate case.