質問

Rcppを使用してcppFunctionモジュールを使用した機能を実装するのに苦労しています。RのNumericVectorタイプを持つRのintersectのようなものを使用する必要があり、R.

と同じように結果を持つ別のNumerIbectorを返します。

このドキュメントはいくつかの助けを借りていますが残念ながら私は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
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top