How to print an R object to stderr in Rcpp?

Viewed 795

I implemented a Python-style dictionary for R, but did not find a good way to raise an error when a given key does not have a value in the dictionary. Calling stop is easy enough, but I would like to tell the user which key has not been found by printing the R object. Right now I have:

Rcpp::Rcout << "Key not found: ";
Rcpp::print(key); # <-- how can I get this on stderr?
Rcpp::stop("Key error!");

This prints the message to stdout, but I'd rather have it on stderr. Probably I'm just missing a function that Rcpp provides?

Here's a MWE:

library(Rcpp)

sourceCpp(code='

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void test(SEXP key) {
  Rcpp::print(key);
  Rcpp::Rcerr << "This does not work: " << key << std::endl;
}

/*** R
test("x")
test(c(1,2,3))
*/

')
3 Answers
Related