質問
Rcpp
を使用してcppFunction
モジュールを使用した機能を実装するのに苦労しています。RのNumericVectorタイプを持つRのintersect
のようなものを使用する必要があり、R.
このドキュメントはいくつかの助けを借りていますが残念ながら私はC ++ ATMのほとんどNoob。
intersect
を使用してcppFunction
R関数をどのように実装することができますか?
ありがとう
解決
unordered_set
のようなものを使用したいと思うでしょう:
ファイルintersect
:
#include <Rcpp.h>
using namespace Rcpp;
// Enable C++11 via this plugin (Rcpp 0.10.3 or later)
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
NumericVector myintersect(NumericVector x, NumericVector y) {
std::vector<double> res;
std::unordered_set<double> s(y.begin(), y.end());
for (int i=0; i < x.size(); ++i) {
auto f = s.find(x[i]);
if (f != s.end()) {
res.push_back(x[i]);
s.erase(f);
}
}
return Rcpp::wrap(res);
}
.
機能をロードしてうまく機能することができます。
library(Rcpp)
sourceCpp(file="myintersect.cpp")
set.seed(144)
x <- c(-1, -1, sample(seq(1000000), 10000, replace=T))
y <- c(-1, sample(seq(1000000), 10000, replace=T))
all.equal(intersect(x, y), myintersect(x, y))
# [1] TRUE
.
しかし、このアプローチはmyintersect.cpp
関数よりも効率的に効率的ではありません。
library(microbenchmark)
microbenchmark(intersect(x, y), myintersect(x, y))
# Unit: microseconds
# expr min lq median uq max neval
# intersect(x, y) 424.167 495.861 501.919 523.7835 989.997 100
# myintersect(x, y) 1778.609 1798.111 1808.575 1835.1570 2571.426 100
. 所属していません StackOverflow