我正在尝试采用以下代码并将其转换为 knitr 块(从 Rcpp 示例中借用):
library(Rcpp)
library(inline)
openMPCode <- '
std::vector<double> x = Rcpp::as<std::vector< double > >(xs);
size_t n = x.size();
#pragma omp parallel for shared(x, n)
for (size_t i=0; i<n; i++) {
x[i] = ::log(x[i]);
}
return Rcpp::wrap(x);
'
## modify the plugin for Rcpp to support OpenMP
settings <- getPlugin("Rcpp")
settings$env$PKG_CXXFLAGS <- paste('-fopenmp', settings$env$PKG_CXXFLAGS)
settings$env$PKG_LIBS <- paste('-fopenmp -lgomp', settings$env$PKG_LIBS)
funOpenMP <- rcpp(signature(xs="numeric"), body=openMPCode, settings=settings)
本质上,主要问题是确保将环境传递到 knitr 块中,以便在编译代码时正确设置PKG_LIBS
and 。块的外观PKG_CXXFLAGS
示例:knitr
```{r engine='Rcpp'}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector openmp_log( NumericVector x ) {
size_t n = x.size();
#pragma omp parallel for
for( size_t i=0; i < n; i++ ) {
x[i] = ::log10( x[i] );
}
return x;
}
```
如果我理解正确,knitr 使用sourceCpp
块中的任何内容来编译它,并将指定的选项传递engine.opts
给sourceCpp
. 因此,我想有两种可能的途径:
设置
engine.opts=list(env=...)
以便通过适当的环境;但是,尝试此操作时出现错误(形式参数“env”与多个实际参数匹配)。A hook / custom chunk option could be used to set the environment, but I'm not sure how this could be done exactly.
This is with knitr 1.0.11 and Rcpp 0.10.2.