R中的交错列表 [英] Interleave lists in R
本文介绍了R中的交错列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在 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')
不使用循环.我知道 mapply 适用于两个列表长度相等的情况.
without using a loop. I know that mapply works for the case where both lists have equal length.
推荐答案
这是一种方法:
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"
正如@James 指出的,既然你需要一个列表,你应该这样做:
As @James points out, since you need a list back, you should do:
(c(a,b))[idx]
这篇关于R中的交错列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文