我是一个C++和Rcpp的新手。假设我有一个向量
t1<-c(1,2,NA,NA,3,4,1,NA,5)
我希望获得t1中所有NA
元素的索引。我可以这样写:
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的等效函数?
(ii) 有没有简化上述函数的方法?特别是,有没有简单的方法将步骤1、2、3组合起来?
which
的线程版本。 - Romain Francois