[英]How do I sort a vector with NA values, and place the NA values at the end of the result in Rcpp or C++?
[英]Detecting and omitting na values from a std vector in Rcpp
我有一個std :: vector; 在檢查其中是否有Na值之后(如果有的話,顯然要刪除Na值),需要對其元素進行匯總。 我必須在Rcpp中進行。 現在,對於Rcpp中的數值向量(NumericVector); 如代碼所示,這非常簡單:
cppFunction("
double res ( NumericVector x){
NumericVector v = x[! is_na(x)];
return sum(v);
}
")
。 因此,對於向量“ x”,它很容易得出如下總和:
x<- c(NaN,1,2)
res(x)
[1] 3
現在為一個std :: vector x; 我該怎么做?
您應該能夠使用RcppHoney (也在CRAN上使用),它將Rcpp Sugar的向量化成語(與R一樣具有向量化的NA測試)帶到任何可迭代的容器中-因此也包括STL容器。
有關將不同的向量類型和類組合為單個標量表達式的示例,請參見例如into vignette 。
// [[Rcpp::export]]
Rcpp::NumericVector example_manually_hooked() {
// We manually hooked std::list in to RcppHoney so we'll create one
std::list< int > l;
l.push_back(1); l.push_back(2); l.push_back(3); l.push_back(4); l.push_back(5);
// std::vector is already hooked in to RcppHoney in default_hooks.hpp so
// we'll create one of those too
std::vector< int > v(l.begin(), l.end());
// And for good measure, let's create an Rcpp::NumericVector which is
// also hooked by default
Rcpp::NumericVector v2(v.begin(), v.end());
// Now do some weird operations incorporating std::vector, std::list,
// Rcpp::NumericVector and some RcppHoney functions and return it. The
// return value will be equal to the following R snippet:
// v <- 1:5
// result <- 42 + v + v + log(v) - v - v + sqrt(v) + -v + 42
// We can store our result in any of RcppHoney::LogicalVector,
// RcppHoney::IntegerVector, or RcppHoney::NumericVector and simply return
// it to R. These classes inherit from their Rcpp counterparts and add a
// new constructor. The only copy of the data, in this case, is when we
// assign our expression to retval. Since it is then a "native" R type,
// returning it is a shallow copy. Alternatively we could write this as:
// return Rcpp::wrap(1 + v + RcppHoney::log(v) - v - 1
// + RcppHoney::sqrt(v) + -v2);
RcppHoney::NumericVector retval
= 42 + l + v + RcppHoney::log(v) - v - l + RcppHoney::sqrt(v) + -v2
+ 42;
return retval;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.