[Rcpp-devel] A clean way to handle character/strings between R and Rcpp

prezzemolo prezzemolo at ctemplar.com
Sat Apr 3 15:45:02 CEST 2021


Hey.I am wondering if there's some general guidance on what the 'right' options are to cleanly handle character arguments passed from R to Rcpp.It is all rather simple: let's say I have a human-readable argument vector c("tree", "herb", "shrub") [It could also be a factor in R], which I can send to an Rcpp function along with other arguments for evaluation.What would be the cleanest way to define those arguments (plant types) in R to then have as little trouble sending them over to Rcpp for use in cases like if() statements?The use of enums comes to mind:// beginningoffileenum class var_type { flower, tree };RCPP_EXPOSED_ENUM_NODECL(var_type)// [[Rcpp::export]]int charHandle1(var_type text_arg = var_type::flower) { if(text_arg == var_type::flower) {   Rcout << static_cast<int>(text_arg) << " says '0 (flower)'.\n"; } else if(text_arg == var_type::tree) {   Rcout << static_cast<int>(text_arg) << " says '1 (tree)'.\n"; } return 0;}// endoffileThis however, doesn't seem to work. I understand R would have to know the var_type for it to work. Then I can do it simply by comparing the const char * argument. This will work, but the strcmp() comparison isn't very straightforward for someone who doesn't know C++ (and perhaps for some other reasons).// [[Rcpp::export]]int charHandle2(const char* text_arg = "flower") { if(strcmp(text_arg, "flower") == 0) {   Rcout << text_arg << " says 'flower'.\n"; } else if(strcmp(text_arg, "tree") == 0) {   Rcout << text_arg << " says 'tree'.\n"; } return 0;}I am looking for some good practice guidance on how to handle this safely and legibly to avoid sending people to function definitions. An argument could be made, for instance, that a list of plant type arguments could be stored as factor in R and then sent and used in some way in Rcpp. What other options are there? To my best knowledge, support for enums is limited - I glanced over the vignettes and couldn't find any significant mention of enums (or factors, really), so I guess some other way of handling such cases should be taken. Has anyone dealt with such cases and has recommendations?Regards,Angelo (Greetings from Genoa)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20210403/b9e77034/attachment.html>


More information about the Rcpp-devel mailing list