Function, pure R to C

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

Arguments

x

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

Value

A C int value.

Declaration

int Rf_asInteger(SEXP x);

In Rinternals.h.

Definition

int asInteger(SEXP x)
{
  int warn = 0, res;

  if (isVectorAtomic(x) && XLENGTH(x) >= 1) {
    switch (TYPEOF(x)) {
    case LGLSXP:
        return IntegerFromLogical(LOGICAL_ELT(x, 0), &warn);
    case INTSXP:
        return INTEGER_ELT(x, 0);
    case REALSXP:
        res = IntegerFromReal(REAL_ELT(x, 0), &warn);
        CoercionWarning(warn);
        return res;
    case CPLXSXP:
        res = IntegerFromComplex(COMPLEX_ELT(x, 0), &warn);
        CoercionWarning(warn);
        return res;
    case STRSXP:
        res = IntegerFromString(STRING_ELT(x, 0), &warn);
        CoercionWarning(warn);
        return res;
    default:
         UNIMPLEMENTED_TYPE("asInteger", x);
      }
  } else if(TYPEOF(x) == CHARSXP) {
      res = IntegerFromString(x, &warn);
      CoercionWarning(warn);
      return res;
  }
  return NA_INTEGER;
}

In coerce.c.

Examples

# Convert an R length one integer vector to a C int number # Please note that the double backslash in "\n" in Rprintf is only required # because of the inlining of the code here. rint_to_cint <- inline::cfunction(c(x = "integer"), ' int x_; x_ = Rf_asInteger(x); Rprintf("x_ is %d\\n", x_); Rprintf("INT_MIN is %d\\n", INT_MIN); return R_NilValue; ' int x_; x_ = Rf_asInteger(x); Rprintf("x_ is %d\\n", x_); Rprintf("INT_MIN is %d\\n", INT_MIN); return R_NilValue; ') invisible(rint_to_cint(NA_integer_))
#> x_ is -2147483648 #> INT_MIN is -2147483648
invisible(rint_to_cint(NaN))
#> x_ is -2147483648 #> INT_MIN is -2147483648
invisible(rint_to_cint(-1L))
#> x_ is -1 #> INT_MIN is -2147483648
invisible(rint_to_cint(0L))
#> x_ is 0 #> INT_MIN is -2147483648
invisible(rint_to_cint(1L))
#> x_ is 1 #> INT_MIN is -2147483648
invisible(rint_to_cint(Inf))
#> Warning: NAs introduced by coercion to integer range
#> x_ is -2147483648 #> INT_MIN is -2147483648