I continued to explore the solution to the pattern problem (e.g. @Sameer answer).
So, I wrote another function, and now the template engine is working.
In an external .cpp file:
#include <Rcpp.h> template <int RTYPE, class T> Vector<RTYPE> na_omit_template(const Vector<RTYPE>& x) { typedef typename Vector<RTYPE>::iterator rvector_it; if (x.size() == 0) { return x; } std::vector<T> out; rvector_it it = x.begin(); for (; it != x.end(); ++it) { if (!Vector<RTYPE>::is_na(*it)) { out.push_back(*it); } } return wrap(out); } // [[Rcpp::export(na_omit_cpp)]] SEXP na_omit(SEXP x) { switch(TYPEOF(x)) { case INTSXP: return na_omit_template<INTSXP, int>(x); case REALSXP: return na_omit_template<REALSXP, double>(x); case LGLSXP: return na_omit_template<LGLSXP, bool>(x); case CPLXSXP: return na_omit_template<CPLXSXP, Rcomplex>(x); case RAWSXP: return na_omit_template<RAWSXP, Rbyte>(x); default: stop("unsupported data type"); } }
This function removes NA values. , that was my original goal.
Unfortunately, at the moment it does not work for all types of vectors , as the examples below R show.
library(Rcpp) sourceCpp('file.cpp') na_omit_cpp(as.integer(c(1, NA, NA, 1, 2, NA)))
Thus, this function works in almost all cases except raw vectors and complex vectors.
current open issues :
- I do not know why this error, and I would like to know why. Any idea?
- The previous template function shown by @Sameer has weird behavior.
- How to make to accept
character vectors?
I was thinking clearly about case STRSXP: return na_omit_template<STRSXP, ?>(x); but this statement does not work, replacing std::string , Rcpp:String with ? .
source share