首页 > 解决方案 > Rcpp 查找唯一字符向量

问题描述

我正在从 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());
    }

标签: rcpp

解决方案


对于不在 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());
}

推荐阅读