EDIT: Thanks to @MatthewLundberg and @Yakk for catching my silly errors.
If what you really want is just faster matching, you should check out Simon Urbanek's fastmatch package. However, Rcpp
does in fact have a sugar in
function which can be used here. in
uses some of the ideas from the fastmatch
package and incorporates them into Rcpp
. I also compare @hadley's solution here.
// [[Rcpp::plugins("cpp11")]]
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::vector<int> sugar_in(IntegerVector x, IntegerVector y) {
LogicalVector ind = in(x, y);
int n = ind.size();
std::vector<int> output;
output.reserve(n);
for (int i=0; i < n; ++i) {
if (ind[i]) output.push_back(i+1);
}
return output;
}
// [[Rcpp::export]]
std::vector<int> which_in(IntegerVector x, IntegerVector y) {
int nx = x.size();
std::unordered_set<int> z(y.begin(), y.end());
std::vector<int> output;
output.reserve(nx);
for (int i=0; i < nx; ++i) {
if (z.find( x[i] ) != z.end() ) {
output.push_back(i+1);
}
}
return output;
}
// [[Rcpp::export]]
std::vector<int> which_in2(IntegerVector x, IntegerVector y) {
std::vector<int> y_sort(y.size());
std::partial_sort_copy (y.begin(), y.end(), y_sort.begin(), y_sort.end());
int nx = x.size();
std::vector<int> out;
for (int i = 0; i < nx; ++i) {
std::vector<int>::iterator found =
lower_bound(y_sort.begin(), y_sort.end(), x[i]);
if (found != y_sort.end()) {
out.push_back(i + 1);
}
}
return out;
}
/*** R
set.seed(123)
library(microbenchmark)
x <- sample(1:100)
y <- sample(1:10000, 1000)
identical( sugar_in(y, x), which(y %in% x) )
identical( which_in(y, x), which(y %in% x) )
identical( which_in2(y, x), which(y %in% x) )
microbenchmark(
sugar_in(y, x),
which_in(y, x),
which_in2(y, x),
which(y %in% x)
)
*/
Calling sourceCpp
on this gives me, from the benchmark,
Unit: microseconds
expr min lq median uq max neval
sugar_in(y, x) 7.590 10.0795 11.4825 14.3630 32.753 100
which_in(y, x) 40.757 42.4460 43.4400 46.8240 63.690 100
which_in2(y, x) 14.325 15.2365 16.7005 17.2620 30.580 100
which(y %in% x) 17.070 21.6145 23.7070 29.0105 78.009 100