RCPP 中的折叠向量
Collapse vectors in Rcpp
我有一个 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"
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- RCPP 中的折叠向量