Collapse vectors in Rcpp

核能气质少年 提交于 2019-12-24 02:06:37

问题


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"


来源:https://stackoverflow.com/questions/35330439/collapse-vectors-in-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!