Search code examples
rrcpprcpp11

Rcpp override summary method for custom class


Suppose I have the following function:

List foo(List x) 
{
   x.attr("class") = "myOwnClass";
   return(x);
}

I whant to override R summary method for foo function output. However the following R-style approach does not work:

List summary.myOwnClass(List x) 
{
   return(x)
}

During compilation I have a error which says that "expected initializer before '.' token".

Please help me to understand how to implement summary function override within Rcpp framework for my customly defined class.

Will be very greatfull for help!


Solution

  • I feel like this is likely a duplicate, but my initial search didn't pull one up. I add a quick answer for now, but if I later find one I'll delete this answer and propose a duplicate.

    The way to solve this issue is to use the export tag to specify the function's R side name as summary.myOwnClass while using something else for the C++ side name; you can't have dots in the middle of a C++ function name (think about, e.g., how member functions are called -- it would be unworkable). So, we do the following

    #include <Rcpp.h>
    
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    List foo(List x)
    {
        x.attr("class") = "myOwnClass";
        return(x);
    }
    
    // [[Rcpp::export(summary.myOwnClass)]]
    List summary(List x)
    {
        return(x);
    }
    
    /*** R
    l <- foo(1:3)
    summary(l)
    */
    

    Then we get the output we expect

    > l <- foo(1:3)
    
    > summary(l)
    [[1]]
    [1] 1
    
    [[2]]
    [1] 2
    
    [[3]]
    [1] 3
    
    attr(,"class")
    [1] "myOwnClass"