문제

Rcpp를 사용하여 cppFunction 모듈과 함수를 구현하는 데 어려움을 겪고 있습니다.두 개의 NumericVector 유형이있는 R의 intersect와 같은 것을 사용하고 R.

와 마찬가지로 결과를 가진 다른 NumericVector를 반환해야합니다.

문서는 도움이되었지만 불행히도 나는C ++ ATM에서 훨씬 많은 놈.

intersect를 사용하여 cppFunction r 함수를 어떻게 구현할 수 있습니까?

감사합니다

도움이 되었습니까?

해결책

unordered_set와 같은 것을 사용하여 intersect를 구현하려는 것입니다.

파일 myintersect.cpp :

#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
.

그러나이 접근법은 itersect 함수보다 효율적으로 덜 효율적인 것처럼 보입니다.

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