rcpp - 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());
}
解决方案
对于不在 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());
}
推荐阅读
- automator - 执行剪贴板内容的全局热键
- python - 使用 readlines() 读取多个打开的文件会导致空数组
- javascript - 如何在不使用jquery的情况下获取另一个html文件,就像通过文档获取它一样
- javascript - 无法在 Mocha 框架 v8.4.0 上访问 foreach 内的全局变量
- python - 无法同时更改所有树视图表中的参数 - python
- blazor - MudBlazor 的 MudChip 默认 true 不起作用
- r - 如何更改 R 中 ggplot (geom_col) 的 Y 范围?
- python - Python3“math.sin”函数返回不正确的结果(角度以弧度为单位。)
- scala - 为什么 List[Int] 可以使用 sorted 方法?
- javascript - reactjs中如何在不同的占位符中渲染不同的组件?