Leonhardt Guass
Leonhardt Guass

Reputation: 793

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)

Upvotes: 1

Views: 727

Answers (2)

thc
thc

Reputation: 9705

Here's a Rcpp solution just for fun:

#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:

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

[[1]]
[1] 1

[[2]]
[1] 3

[[3]]
[1] 2

[[4]]
[1] 4

Upvotes: 2

akrun
akrun

Reputation: 887088

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.

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

c(rbind(s1, s2))

Upvotes: 3

Related Questions