Function, pure R to R Needs PROTECT()

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.

Arguments

x

a pointer SEXP.

Value

A pointer SEXP, referring to an object of type CHARSXP.

Declaration

SEXP asChar(SEXP x);

In Rinternals.h.

Definition

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.

See also

Examples

# 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
invisible(print_char(c("charcoal", "coal")))
#> charcoal
invisible(print_char(NA_character_))
#> NA
# Convert from LGLSXP to CHARSXP invisible(print_char(TRUE))
#> TRUE
invisible(print_char(FALSE))
#> FALSE
invisible(print_char(NA))
#> NA
# Convert from INTSXP to CHARSXP invisible(print_char(-1L))
#> -1
invisible(print_char(1L))
#> 1
invisible(print_char(NA_integer_))
#> NA
# Convert from REALSXP to CHARSXP invisible(print_char(1.0))
#> 1
invisible(print_char(-1))
#> -1
invisible(print_char(NA_real_))
#> NA
# Convert from CPLXSXP to CHARSXP invisible(print_char(2+5i))
#> 2+5i
# Convert from SYMSXP to CHARSXP invisible(print_char(as.symbol('a')))
#> a
# Coercion from other object types to CHARSXP # results in NA: # From VECSXP to CHARSXP invisible(print_char(list(a = 'b')))
#> NA
# From ENVSXP to CHARSXP invisible(print_char(.GlobalEnv))
#> NA
# From CLOSXP to CHARSXP invisible(print_char(function() {}))
#> NA
# From EXPRSXP to CHARSXP invisible(print_char(expression()))
#> NA
# From LANGSXP to CHARSXP invisible(print_char(~ 2 + x))
#> NA