Rcpp 中的折叠向量 [英] Collapse vectors in Rcpp
问题描述
我有一个 Rcpp 函数,它为我提供了一个包含一些字符串向量 (std::vector) 的列表.
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"
我想得到这样的东西:
[[1]] [1] "010000"
[[2]] [1] "000001"
[[3]] [1] "010000"
[[4]] [1] "000100"
现在我正在使用:apply(do.call(rbind,myFunctioninCPP(),1,paste0,collapse="")
得到我想要的.
Now I am using:
apply(do.call(rbind,myFunctioninCPP(),1,paste0,collapse="")
to get what I want.
我想知道是否有可能以这种方式获得更开箱即用"的 myFunctioninCPP() 结果.有什么建议吗?
I'm wondering if its possible to get this more "outofthebox" getting the result of myFunctioninCPP() in such way. Any suggestions?
推荐答案
使用下面的代码,为了演示目的,它以一个普通的 IntegerVector
作为输入.std::ostringstream
的使用相当简单,在尝试执行像您这样的操作时会派上用场.
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();
}
现在,使用 sourceCpp
将函数加载到 R 中,并从 *apply
循环内部调用它.
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"
这篇关于Rcpp 中的折叠向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!