Rf_asInteger: Convert an R scalar integer vector to a C int

Description Arguments Value Declaration Definition Examples

Description

\Sexpr[results=rd, stage=render]{c3po:::badge('fnp')} \Sexpr[results=rd, stage=render]{c3po:::badge('r2c')}

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

1

In Rinternals.h.

Definition

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 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;
 ')
invisible(rint_to_cint(NA_integer_))
invisible(rint_to_cint(NaN))
invisible(rint_to_cint(-1L))
invisible(rint_to_cint(0L))
invisible(rint_to_cint(1L))
invisible(rint_to_cint(Inf))

ramiromagno/c3po documentation built on Jan. 5, 2021, 8:01 p.m.