gpt4 book ai didi

r - 在Rcpp中对命名的数值向量进行排序

转载 作者:行者123 更新时间:2023-12-03 17:15:53 24 4
gpt4 key购买 nike

在一个函数中,我想计算数值,给它们命名,并在Rcpp中返回排序后的NumericVector。我可以对向量进行排序(使用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在其评论中给出的提示,我发现x的名称只是另一个向量。因此,我搜索了使用另一个向量对向量进行排序的方法。使用this SO answer,我提出了以下两种解决方案:

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

关于r - 在Rcpp中对命名的数值向量进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60254915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com