相关疑难解决方法(0)

相当于Rcpp中的'which'函数

我是C++和Rcpp的新手.假设,我有一个向量

t1<-c(1,2,NA,NA,3,4,1,NA,5)
Run Code Online (Sandbox Code Playgroud)

我想得到一个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;
} …
Run Code Online (Sandbox Code Playgroud)

r rcpp

3
推荐指数
2
解决办法
3454
查看次数

标签 统计

r ×1

rcpp ×1