SEXP ToRMatrix(const Matrix &m, const std::vector<std::string> &rownames, const std::vector<std::string> &colnames){ if (!rownames.empty() && rownames.size() != m.nrow()) { report_error("In ToRMatrix: Vector of row names does not match " "the number of rows in m."); } else if (!colnames.empty() && colnames.size() != m.ncol()) { report_error("In ToRMatrix: Vector of column names does not match " "the number of columns in m."); } SEXP ans; PROTECT(ans = Rf_allocMatrix(REALSXP, m.nrow(), m.ncol())); double *data = REAL(ans); std::copy(m.begin(), m.end(), data); SEXP r_dimnames; PROTECT(r_dimnames = Rf_allocVector(VECSXP, 2)); SET_VECTOR_ELT( r_dimnames, 0, rownames.empty() ? R_NilValue : CharacterVector(rownames)); SET_VECTOR_ELT( r_dimnames, 1, colnames.empty() ? R_NilValue : CharacterVector(colnames)); Rf_dimnamesgets(ans, r_dimnames); UNPROTECT(2); return ans; }
CharacterVector default_chars(SEXP x, R_xlen_t len) { if (Rf_isNull(x)) return CharacterVector(len); return x; }