1 Passing Numerical Vectors

1.1 NA

#include <R.h>
#include <Rinternals.h>

SEXP square (SEXP x) {
  R_len_t i, n = length (x), nProtected = 0;
  SEXP y = PROTECT (allocVector (REALSXP, n)); nProtected++;
  double *v = REAL (y), *z;
  if (TYPEOF (x) == REALSXP) {
    z = REAL (x);
  } else {
    z = REAL (coerceVector (x, REALSXP));
  }
  for (i = 0; i < n; i++) {
    v[i] = R_NaInt == z[i] ? -1 : z[i] * z[i];
  }
  UNPROTECT (nProtected);
  return (y);
}
.Call("square", as.double(c(1, NA, 2, "3", -1)))
## [1]  1 NA  4  9  1
.Call("square", as.double(c(1, NA, 2, "a", -1)))
## Warning: NAs introduced by coercion
## [1]  1 NA  4 NA  1