Hi all,

I've attached a simple implementation of unique for numeric, integer,
logical, and character vectors.  To do that I have four C++ function,
along the lines of :

std::tr1::unordered_set<double> unique1(NumericVector x) {
  return std::tr1::unordered_set<double>(x.begin(), x.end());
}

and then one exported function:

// [[Rcpp::export]]
RObject unique2(RObject x) {
  switch(x.sexp_type()) {
    case REALSXP:
      return wrap(unique1(as<NumericVector>(x)));
      break;
    case INTSXP:
      return wrap(unique1(as<IntegerVector>(x)));
      break;
    case CHARSXP:
      return wrap(unique1(as<CharacterVector>(x)));
      break;
    case LGLSXP:
      return wrap(unique1(as<LogicalVector>(x)));
      break;
  }
  Rf_error("Unsupported type");

}

Is this right way to go about it?  (I realise I could probably write a
template for the individual unique1 methods, but I'd like to keep it
simple for now).

Thanks!

Hadley

-- 
RStudio / Rice University
http://had.co.nz/
#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;


std::tr1::unordered_set<double> unique1(NumericVector x) {
  return std::tr1::unordered_set<double>(x.begin(), x.end());
}
std::tr1::unordered_set<int> unique1(IntegerVector x) {
  return std::tr1::unordered_set<int>(x.begin(), x.end());
}
std::tr1::unordered_set<bool> unique1 (LogicalVector x) {
  return std::tr1::unordered_set<bool>(x.begin(), x.end());
}
std::tr1::unordered_set<std::string> unique1(CharacterVector x) {
  std::tr1::unordered_set<std::string> seen;

  for(CharacterVector::iterator it = x.begin(); it != x.end(); ++it) {
    seen.insert(std::string(*it));
  } 
  return(seen);
}

// [[Rcpp::export]]
RObject unique2(RObject x) {
  switch(x.sexp_type()) {
    case REALSXP: 
      return wrap(unique1(as<NumericVector>(x)));
      break;
    case INTSXP: 
      return wrap(unique1(as<IntegerVector>(x)));
      break;
    case CHARSXP: 
      return wrap(unique1(as<CharacterVector>(x)));
      break;
    case LGLSXP: 
      return wrap(unique1(as<LogicalVector>(x)));
      break;
  }
  Rf_error("Unsupported type");

}

_______________________________________________
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to