Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Interleave lists in R

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's one 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 you need a list back, you should do:

(c(a,b))[idx]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...