c++ - Rcpp 中的折叠 vector

标签 c++ r vector rcpp

我有一个 Rcpp 函数,它为我提供了一个包含一些字符串 vector (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"

关于c++ - Rcpp 中的折叠 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35330439/

相关文章:

c++ - 返回值优化和析构函数调用

c++ - 插入元素后 vector 的容量增加?

c++ - vector.erase() 和 remove_if() 有问题

android - 如何为矢量绘图添加阴影?

c++ - 从 C++ 中的 QML-矩形请求键盘焦点

c++ - 在什么情况下 delete 运算符会抛出错误?

r - 如何将 AR(MA) 模型应用于预白化信号?

r - 如何使用r省略data.frame中单词的倒数

r - 基于x轴改变ggplot2中密度图的颜色

c++ - 如果C++构造函数不返回任何内容,如何在表达式中使用它?