Collapse vectors in Rcpp

2019-07-12 21:50发布

问题:

I have an Rcpp function that gives me as result an list with some vectors of strings (std::vector).

 [[1]] [1] "0" "1" "0" "0" "0" "0"
 [[2]] [1] "0" "0" "0" "0" "0" "1"
 [[3]] [1] "0" "1" "0" "0" "0" "0"
 [[4]] [1] "0" "0" "0" "1" "0" "0"

I want to get these things like this:

[[1]] [1] "010000"
[[2]] [1] "000001" 
[[3]] [1] "010000"
[[4]] [1] "000100"

Now I am using: apply(do.call(rbind,myFunctioninCPP(),1,paste0,collapse="") to get what I want.

I'm wondering if its possible to get this more "outofthebox" getting the result of myFunctioninCPP() in such way. Any suggestions?

回答1:

Take the following code which, for demonstration purposes, takes an ordinary IntegerVector as input. The use of std::ostringstream is rather straightforward and comes in handy when trying to perform operations like yours.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
String concat(IntegerVector x) {

  // convert intput to 'CharacterVector'
  int nChar = x.size();
  CharacterVector y = as<CharacterVector>(x);

  // initialize string output stream
  std::ostringstream ossOut;

  // concatenate input
  for (int i = 0; i < nChar; i++)
    ossOut << y[i];

  return ossOut.str();  
}

Now, load the function into R using sourceCpp and call it from inside an *apply loop.

## source c++ function
library(Rcpp)
sourceCpp("~/work/programming/concat.cpp")

## test run
lst <- list(c(0, 1, 0, 0, 0, 0), 
            c(0, 0, 0, 0, 0, 1), 
            c(0, 1, 0, 0, 0, 0), 
            c(0, 0, 0, 1, 0, 0)) 

lapply(lst, concat)
[[1]]
[1] "010000"

[[2]]
[1] "000001"

[[3]]
[1] "010000"

[[4]]
[1] "000100"


标签: c++ r vector rcpp