RCPP 中的折叠向量

Collapse vectors in Rcpp

本文关键字:向量 折叠 RCPP      更新时间:2023-10-16

我有一个 Rcpp 函数,结果给了我一个包含一些字符串向量的列表 (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"

我想得到这样的东西:

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

现在我正在使用: apply(do.call(rbind,myFunctioninCPP(),1,paste0,collapse="")得到我想要的。

我想知道是否有可能以这种方式获得 myFunctioninCPP() 的结果,使其更加"开箱即用"。有什么建议吗?

采用以下代码,出于演示目的,该代码将普通IntegerVector作为输入。std::ostringstream的使用非常简单,在尝试执行像您这样的操作时会派上用场。

#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();  
}

现在,使用 sourceCpp 将函数加载到 R 中,并从 *apply 循环中调用它。

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