Rcpp找到唯一的字符向量



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

有一个练习是在Rcpp中使用unordered_set实现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());
}

最新更新