سؤال

أواجه صعوبة في تنفيذ وظيفة مع Rcpp الوحدة باستخدام cppFunction.أحتاج إلى استخدام شيء مثل R intersect باستخدام نوعين NumericVector وإرجاع NumericVector آخر مع النتيجة، تمامًا كما في R.

هذا لقد كان المستند مفيدًا بعض الشيء ولكن لسوء الحظ فأنا مبتدئ إلى حد كبير في أجهزة الصراف الآلي C++.

كيف يمكنني تنفيذ intersect وظيفة R مع cppFunction ?

شكرًا

هل كانت مفيدة؟

المحلول

ربما ترغب في استخدام شيء مثل 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