相当于 Rcpp 中的“哪个"函数 [英] equivalent of 'which' function in Rcpp
问题描述
我是 C++ 和 Rcpp 的新手.假设,我有一个向量
I'm a newbie to C++ and Rcpp. Suppose, I have a vector
t1<-c(1,2,NA,NA,3,4,1,NA,5)
并且我想获得 NA
的 t1 元素的索引.我可以写:
and I want to get a index of elements of t1 that are NA
. I can write:
NumericVector retIdxNA(NumericVector x) {
// Step 1: get the positions of NA in the vector
LogicalVector y=is_na(x);
// Step 2: count the number of NA
int Cnt=0;
for (int i=0;i<x.size();i++) {
if (y[i]) {
Cnt++;
}
}
// Step 3: create an output matrix whose size is same as that of NA
// and return the answer
NumericVector retIdx(Cnt);
int Cnt1=0;
for (int i=0;i<x.size();i++) {
if (y[i]) {
retIdx[Cnt1]=i+1;
Cnt1++;
}
}
return retIdx;
}
然后我得到
retIdxNA(t1)
[1] 3 4 8
我在想:
(i) 在 Rcpp 中是否有任何等效的 which
?
(i) is there any equivalent of which
in Rcpp?
(ii) 有没有办法让上述函数更短/更清晰?特别是,有没有什么简单的方法可以将上面的步骤 1、2、3 结合起来?
(ii) is there any way to make the above function shorter/crisper? In particular, is there any easy way to combine the Step 1, 2, 3 above?
推荐答案
RcppArmadillo 的最新版本 具有识别有限和非有限值的索引的功能.
Recent version of RcppArmadillo have functions to identify the indices of finite and non-finite values.
所以这段代码
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::uvec whichNA(arma::vec x) {
return arma::find_nonfinite(x);
}
/*** R
t1 <- c(1,2,NA,NA,3,4,1,NA,5)
whichNA(t1)
*/
产生您想要的答案(在 C/C++ 中将非 1 模块化,因为它们是从零开始的):
yields your desired answer (module the off-by-one in C/C++ as they are zero-based):
R> sourceCpp("/tmp/uday.cpp")
R> t1 <- c(1,2,NA,NA,3,4,1,NA,5)
R> whichNA(t1)
[,1]
[1,] 2
[2,] 3
[3,] 7
R>
如果您首先创建要子集的序列,Rcpp 也可以这样做:
Rcpp can do it too if you first create the sequence to subset into:
// [[Rcpp::export]]
Rcpp::IntegerVector which2(Rcpp::NumericVector x) {
Rcpp::IntegerVector v = Rcpp::seq(0, x.size()-1);
return v[Rcpp::is_na(x)];
}
添加到上面的代码产生:
Added to code above it yields:
R> which2(t1)
[1] 2 3 7
R>
Rcpp 中的逻辑子集也有些新.
The logical subsetting is also somewhat new in Rcpp.
这篇关于相当于 Rcpp 中的“哪个"函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!