Rf_asChar.Rd
Coerce an R object to a scalar string, i.e., to an R object of type
CHARSXP
. This object type should only be used internally, i.e.,
it should not be returned back to R.
x | a pointer |
---|
A pointer SEXP
, referring to an object of type
CHARSXP
.
SEXP asChar(SEXP x);
In Rinternals.h.
SEXP asChar(SEXP x) { if (isVectorAtomic(x) && XLENGTH(x) >= 1) { int w, d, e, wi, di, ei; char buf[MAXELTSIZE]; /* Probably 100 would suffice */ switch (TYPEOF(x)) { case LGLSXP: if (LOGICAL(x)[0] == NA_LOGICAL) return NA_STRING; if (LOGICAL(x)[0]) sprintf(buf, "TRUE"); else sprintf(buf, "FALSE"); return mkChar(buf); case INTSXP: if (INTEGER(x)[0] == NA_INTEGER) return NA_STRING; snprintf(buf, MAXELTSIZE, "%d", INTEGER(x)[0]); return mkChar(buf); case REALSXP: PrintDefaults(); formatReal(REAL(x), 1, &w, &d, &e, 0); return mkChar(EncodeReal0(REAL(x)[0], w, d, e, OutDec)); case CPLXSXP: PrintDefaults(); formatComplex(COMPLEX(x), 1, &w, &d, &e, &wi, &di, &ei, 0); return mkChar(EncodeComplex(COMPLEX(x)[0], w, d, e, wi, di, ei, OutDec)); case STRSXP: return STRING_ELT(x, 0); default: return NA_STRING; } } else if(TYPEOF(x) == CHARSXP) { return x; } else if(TYPEOF(x) == SYMSXP) return PRINTNAME(x); return NA_STRING; }
In util.c.
# Coerces an R object to an object of type CHARSXP print_char <- inline::cfunction(c(x = "any"), ' const char * x_; x_ = R_CHAR(Rf_asChar(x)); Rprintf("%s\\n", x_); return R_NilValue; ' const char * x_; x_ = R_CHAR(Rf_asChar(x)); Rprintf("%s\\n", x_); return R_NilValue; ') # Convert from STRSXP to CHARSXP invisible(print_char("coal"))#> coal#> charcoal#> NA#> TRUE#> FALSE#> NA#> -1#> 1#> NA#> 1#> -1#> NA#> 2+5i#> a# Coercion from other object types to CHARSXP # results in NA: # From VECSXP to CHARSXP invisible(print_char(list(a = 'b')))#> NA#> NA#> NA#> NA#> NA