Rcpp 查找唯一特征向量

Rcpp find unique character vectors

我正在从 Hadley Wickham 的 Advance R 学习 Rcpp:http://adv-r.had.co.nz/Rcpp.html

有一项练习使用 unordered_set 在 Rcpp 中实现 R 函数 unique()(挑战:在一行中完成!)。该解决方案在数字向量中找到唯一数字。我正在尝试使用第二个代码块在字符向量中查找唯一字符,这会产生错误。关于如何手动实现这个简单功能的任何想法?谢谢!

// [[Rcpp::export]]
    std::unordered_set<double> uniqueCC(NumericVector x) {
      return std::unordered_set<double>(x.begin(), x.end());
    }
    
    
    
    // [[Rcpp::export]]
    std::unordered_set<String> uniqueCC(CharacterVector x) {
      return std::unordered_set<String>(x.begin(), x.end());
    }

对于不在 STL 库中的对象类型,您需要定义自己的哈希函数。 String(大写S)是一个Rcpp对象。

最简单的方法是使用 Rcpp 转换为普通 STL 对象的能力。

// [[Rcpp::export]]
std::unordered_set<std::string> uniqueCC(CharacterVector x) {
  auto xv = Rcpp::as<std::vector<std::string>>(x);
  return std::unordered_set<std::string>(xv.begin(), xv.end());
}

> x <- sample(letters, 1000, replace=T)
> uniqueCC(x)
 [1] "r" "o" "c" "n" "f" "s" "y" "l" "i" "j" "m" "v" "t" "p" "u" "x" "w" "k" "g" "a" "d" "q" "z" "b" "h" "e"

或者,您可以接受一个 STL 字符串向量,然后 Rcpp 魔术将完成剩下的工作:

// [[Rcpp::export]]
std::unordered_set<std::string> uniqueCC(const std::vector<std::string> & x) {
  return std::unordered_set<std::string>(x.begin(), x.end());
}