equivalent of 'which' function in Rcpp
r, rcpp
Solution
Recent version of RcppArmadillo have functions to identify the indices of finite and non-finite values.
So this code
#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)
*/
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 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>
The logical subsetting is also somewhat new in Rcpp.
Problem
I'm a newbie to C++ and Rcpp. Suppose, I have a vector ``` t1<-c(1,2,NA,NA,3,4,1,NA,5) ``` 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; } ``` then I get ``` retIdxNA(t1) [1] 3 4 8 ``` I was wondering: (i) is there any equivalent of `which` in Rcpp? (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?