r - 在 Rcpp 中对命名的数字向量进行排序
问题描述
在一个函数中,我想计算数值,给它们命名并返回一个NumericVector
在 Rcpp 中排序的值。我可以对向量进行排序(使用this),但值名称的顺序保持不变。
library(Rcpp)
x <- c(a = 1, b = 5, c = 3)
cppFunction('
NumericVector foo(NumericVector x) {
std::sort(x.begin(), x.end());
return(x);
}')
foo(x)
## a b c
## 1 3 5
我希望函数返回这个:
## a c b
## 1 3 5
可能吗?我怎样才能做到这一点?
解决方案
使用 Dirk 在他的评论中给出的提示,我发现 names ofx
只是另一个向量。因此,我搜索了使用另一个向量对向量进行排序。使用这个 SO 答案我想出了以下两个解决方案:
library(Rcpp)
x = c(a = 1, b = 5, c = 3, d = -3.2)
cppFunction('
NumericVector foo1(NumericVector x) {
IntegerVector idx = seq_along(x) - 1;
std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
return x[idx];
}')
foo1(x)
## d a c b
## -3.2 1.0 3.0 5.0
cppFunction('
NumericVector foo2(NumericVector x) {
IntegerVector idx = seq_along(x) - 1;
//// Ordered indices based on x:
std::sort(idx.begin(), idx.end(), [&](int i, int j){return x[i] < x[j];});
//// Get the names of x:
CharacterVector names_of_x = x.names();
//// y vector is sorted x
NumericVector y = x[idx];
//// Assign sorted names to y vector as names
y.attr("names") = names_of_x[idx];
return y;
}')
foo2(x)
## d a c b
## -3.2 1.0 3.0 5.0
推荐阅读
- java - java.time.format.DateTimeParseException:无法在索引 0 处解析文本“2020052”
- python - 此示例中的 HTML 中 svg 的正确 xpath 是什么?
- python - 在 pandas 数据框中删除多个条件下的行(基于 2 列)
- linux - 如何根据模式从集群中 grep/awk 多行?
- python-3.x - 如何使用 request-mock 来测试带有请求的自定义身份验证处理程序?
- python - 如何在 Heroku(使用 python)上的 web 和 worker(不同的 dynos)之间通信数据?
- bash - 带 bash 的条件否定
- javascript - 用第一个模态替换第二个模态
- javascript - 无法从搜索页面抓取所有结果
- javascript - 当函数包含异步操作时,如何按顺序对同一函数进行多次调用