【发布时间】:2014-05-24 20:28:52
【问题描述】:
我是 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步结合起来?
【问题讨论】:
-
另请参阅github.com/romainfrancois/Rcpp-book/blob/master/chapters/… 了解
which的线程版本 -
@RomainFrancois,感谢分享链接。
-
很高兴您发现它很有用。我知道它需要重写。但是基本的想法就在那里。