Skip to content

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

6 messages · Wei Zhang, Dominick Samperi, Dirk Eddelbuettel

#
R has its own way of representing NA's. See, for example, the fts
package at CRAN,
in particular, the file src/tslib/tslib/utils/numeric.traits.hpp.

Dominick
On Mon, Feb 7, 2011 at 5:23 PM, WEI ZHANG <aweizhang at gmail.com> wrote:
#
I sent you an overly complicated reply. Take a look
at R/include/R_ext/Arith.h where REAL_NA is defined...
On Mon, Feb 7, 2011 at 5:33 PM, Dominick Samperi <djsamperi at gmail.com> wrote:
#
I figured I can actually use NA_LOGICAL, NA_INTEGER , NA_REAL...

Thanks for your help. 


-----Original Message-----
From: Dominick Samperi [mailto:djsamperi at gmail.com] 
Sent: Monday, February 07, 2011 5:33 PM
To: WEI ZHANG
Cc: rcpp-devel at r-forge.wu-wien.ac.at
Subject: Re: [Rcpp-devel] passing NA from C++ to R

R has its own way of representing NA's. See, for example, the fts
package at CRAN,
in particular, the file src/tslib/tslib/utils/numeric.traits.hpp.

Dominick
On Mon, Feb 7, 2011 at 5:23 PM, WEI ZHANG <aweizhang at gmail.com> wrote:
NA
#
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
#
On 7 February 2011 at 17:50, WEI ZHANG wrote:
| I figured I can actually use NA_LOGICAL, NA_INTEGER , NA_REAL...

NA_LOGICAL and NA_INTEGER are R-only so you can't interchange with other
code.  NA_REAL, and the +/- Inf values conform to an IEEE standard so you are
likely to have better luck with those... 

Dirk