Function, pure R to C

Converts a scalar (length one) double vector (SEXP) x to a C double.

Arguments

x

a pointer SEXP, referring to an object of type REALSXP.

Value

A C double value.

Declaration

double asReal(SEXP x);

In Rinternals.h.

Definition

double asReal(SEXP x)
{
 int warn = 0;
 double res;

 if (isVectorAtomic(x) && XLENGTH(x) >= 1) {
   switch (TYPEOF(x)) {
     case LGLSXP:
         res = RealFromLogical(LOGICAL_ELT(x, 0), &warn);
         CoercionWarning(warn);
         return res;
     case INTSXP:
         res = RealFromInteger(INTEGER_ELT(x, 0), &warn);
         CoercionWarning(warn);
         return res;
     case REALSXP:
         return REAL_ELT(x, 0);
     case CPLXSXP:
         res = RealFromComplex(COMPLEX_ELT(x, 0), &warn);
         CoercionWarning(warn);
         return res;
     case STRSXP:
         res = RealFromString(STRING_ELT(x, 0), &warn);
         CoercionWarning(warn);
         return res;
     default:
         UNIMPLEMENTED_TYPE("asReal", x);
   }
 } else if(TYPEOF(x) == CHARSXP) {
   res = RealFromString(x, &warn);
   CoercionWarning(warn);
   return res;
 }
 return NA_REAL;
}

In coerce.c.

Examples

# Convert an R length one integer vector to a C double number # Please note that the double backslash in "\n" in Rprintf is only required # because of the inlining of the code here. rdouble_to_cdouble <- inline::cfunction(c(x = "double"), ' double x_; x_ = Rf_asReal(x); Rprintf("x_ is %f\\n", x_); return R_NilValue; ' double x_; x_ = Rf_asReal(x); Rprintf("x_ is %f\\n", x_); return R_NilValue; ') invisible(rdouble_to_cdouble(NA_real_))
#> x_ is nan
invisible(rdouble_to_cdouble(NaN))
#> x_ is nan
invisible(rdouble_to_cdouble(-1))
#> x_ is -1.000000
invisible(rdouble_to_cdouble(0))
#> x_ is 0.000000
invisible(rdouble_to_cdouble(1))
#> x_ is 1.000000
invisible(rdouble_to_cdouble(Inf))
#> x_ is inf