R中的交织列表

假设我在R中有两个列表,长度不一定相等,例如:

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

构造交错元素列表的最佳方法是什么,一旦添加了较短列表的元素,则将较长列表的其余元素添加到末尾,例如:

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

不使用循环。我知道mapply适用于两个列表长度相等的情况。


ABOUTYOU
浏览 522回答 3
3回答

海绵宝宝撒

在调查类似的问题,我碰到这个由格罗腾迪克的Gabor(即漂亮的解决方案@GGrothendieck?)某些情况下:c(rbind(a,b))当a和b都是列表,或者当a和b都是向量时,这同样有效。这不是OP问题的精确解决方案,因为当a和b具有不同的长度时,它将回收较短序列的元素,并显示警告。但是,由于此解决方案简单而优雅,并且提供了一个非常相似的问题的答案-一个像我这样的人的问题,他们因此找到了进入此页面的方式-似乎值得补充。

慕田峪9158850

interleave(a,&nbsp;b)#&nbsp;unlist(interleave(a,&nbsp;b))#&nbsp;[1]&nbsp;"a.1"&nbsp;"b.1"&nbsp;"a.2"&nbsp;"b.2"&nbsp;"a.3"&nbsp;"b.3"&nbsp;"b.4"interleave&nbsp;<-&nbsp;function(a,&nbsp;b)&nbsp;{&nbsp; &nbsp;&nbsp;shorter&nbsp;<-&nbsp;if&nbsp;(length(a)&nbsp;<&nbsp;length(b))&nbsp;a&nbsp;else&nbsp;b &nbsp;&nbsp;longer&nbsp;&nbsp;<-&nbsp;if&nbsp;(length(a)&nbsp;>=&nbsp;length(b))&nbsp;a&nbsp;else&nbsp;b &nbsp;&nbsp;slen&nbsp;<-&nbsp;length(shorter) &nbsp;&nbsp;llen&nbsp;<-&nbsp;length(longer) &nbsp;&nbsp;index.short&nbsp;<-&nbsp;(1:slen)&nbsp;+&nbsp;llen &nbsp;&nbsp;names(index.short)&nbsp;<-&nbsp;(1:slen) &nbsp;&nbsp;lindex&nbsp;<-&nbsp;(1:llen)&nbsp;+&nbsp;slen &nbsp;&nbsp;names(lindex)&nbsp;<-&nbsp;1:llen &nbsp;&nbsp;sindex&nbsp;<-&nbsp;1:slen &nbsp;&nbsp;names(sindex)&nbsp;<-&nbsp;1:slen &nbsp;&nbsp;index&nbsp;<-&nbsp;c(sindex,&nbsp;lindex) &nbsp;&nbsp;index&nbsp;<-&nbsp;index[order(names(index))] &nbsp;&nbsp;return(c(a,&nbsp;b)[index])}
打开App,查看更多内容
随时随地看视频慕课网APP