[Rcpp-devel] passing NA from C++ to R

Dirk Eddelbuettel edd at debian.org
Mon Feb 7 23:51:11 CET 2011


On 7 February 2011 at 17:23, WEI ZHANG wrote:
| I would like to know how can I pass NA from C++ to R.

Just assign it, using the constants defined in Rmath.h:

R> suppressMessages(library(inline))
R> src <- 'Rcpp::NumericVector v(4);
+         v[0] = R_NegInf;  // -Inf
+         v[1] = NA_REAL;   // NA
+         v[2] = R_PosInf;  // Inf
+         v[3] = 42;        // see the Hitchhiker Guide
+         return Rcpp::wrap(v);'
R> fun <- cxxfunction(signature(), src, plugin="Rcpp")
R> fun()
[1] -Inf   NA  Inf   42
R> 

| For example, for any integer in C++ , if == -999, I would like to set to NA to
| pass to R.

This works for _floats_ but not integers, so you have to convert to 'numeric'
first,  You can the convert -999.0 to NA_REAL if you like.  As as seen above,
R will see it as NA.

Hope this helps, Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list