Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

When writing an R package wrapping some C++ data structures, using Rcpp Modules is a convenient option. After exposing a class to R, it can be used to easily create new instances of that class.

As an example, let us look at the Uniform class of the Rcpp Modules vignette:

After sourcing the file the Uniform class can be used:

C++ object <0x55fd63177450> of class 'Uniform' <0x55fd63788a20>


What happens now, is that the uniform instance calls its default print method – which results in a fairly uninformative display. It would be nice if the printer of the instances could be customized to provide more information about the specific object.

## Customize the Printer

It is possible to make use of the underlying S4 structure of the exposed C++ classes:

[1] TRUE

[1] "Rcpp_Uniform"
attr(,"package")
[1] ".GlobalEnv"


For the Uniform class this is Rcpp_Uniform. To obtain a custom printer the last step now is to set the method show and define the function which should be used as printer:

 Hi, I am an uniform object!

I was initialized with a minimum value of 0
and a maximum value of 10.

Therefore my range is 10.


This works very nicely. Now it is possible to provide some more informations about a new Uniform instance. One thing to note is that setMethod returns the method name as string, which we assign to an otherwise unused variable.

## Use in Packages

To get that print method as a default printer after exposing the C++ class to R within a package, it is sufficient to create a R file (e.g. R/uniform_printer.R) and put the following code in there: