简体   繁体   English

R将两个列表合并为一个,从每个列表中交替绘制元素

[英]R merge two lists into one, drawing elements from each list alternatively

I want to merge two lists into one, drawing elements from each list alternatively 我想将两个列表合并为一个,或者从每个列表中绘制元素

Example: 例:

s1 <- list(1,2)
s2 <- list(3,4)

I do not want: 我不想:

c(s1,s2)

Instead, I want 相反,我想要

list(1,3,2,4)

Using Map append the corresponding list elements of 's1' and 's2' as a list and then with do.call(c , flatten the nested list to a list of depth 1. 使用Map将's1'和's2'的相应list元素添加为list ,然后使用do.call(c ,将嵌套列表展平为深度为1的列表。

do.call(c, Map(list, s1, s2))

Or another option is to rbind the list elements into a matrix and remove the dim attributes with c 或者另一个选择是将list元素rbindmatrix然后使用c删除dim属性

c(rbind(s1, s2))

Here's a Rcpp solution just for fun: 这是一个有趣的Rcpp解决方案:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List abc(List x1, List x2) {
  if(x1.size() != x2.size()) throw exception("lists must be same size");
  List new_list(x1.size()*2);
  for(size_t i=0; i<x1.size(); i++ ) {
    new_list[2*i] = x1[i];
    new_list[2*i+1] = x2[i];
  }
  return(new_list);
}

R: R:

library(Rcpp)
sourceCpp("abc.cpp")
abc(s1,s2)

[[1]]
[1] 1

[[2]]
[1] 3

[[3]]
[1] 2

[[4]]
[1] 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM