与Rcpp相交功能

Pan*_*ane 1 c++ r rcpp

我很难用Rcpp模块实现一个函数cppFunction.我需要使用类似R的intersect两个NumericVector类型,并返回另一个NumericVector与结果,就像在R.

这个文档有一些帮助,但不幸的是我在C++ atm中几乎是一个菜鸟.

我怎么能用intersectR函数实现cppFunction

谢谢

jos*_*ber 6

你可能想要使用类似的东西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);
}
Run Code Online (Sandbox Code Playgroud)

我们可以加载该函数并验证它是否有效:

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
Run Code Online (Sandbox Code Playgroud)

但是,似乎这种方法的效率低于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
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.FWIW我们还有一个丑陋的大写宏给我们`RCPP_UNORDERED_SET`,无论编译器如何.但通过插件询问更优雅:) (3认同)