rfunctionmethodshidden

Using hidden functions when defining a new method for a generic in R


I want to create a new subclass of the mesh3d S3 object class, and a corresponding method for rgl::shade3d. The new method will be closely modelled on the existing shade3d function but with different defaults. This is what I tried initially:

library(rgl)

# Create a test object
obj <- translate3d(tetrahedron3d(col = "red"), 0, 0, 0)

# Create a new S3 subclass 
obj <- structure(obj, class = c("myclass", "mesh3d", "shape3d"))

# Creating a shade3d method for myclass
shade3d.myclass <- function(mesh, ...) {
  shade3d(mesh, ..., lit = F)
}

shade3d(obj)
# Error: C stack usage  15923488 is too close to the limit

As far as I can figure out, this is because the function tries to call itself. To prevent this, I need to specify the method I'm referring to within my function.

methods(shade3d)
# [1] shade3d.mesh3d*      shade3d.myclass      shade3d.shapelist3d*

shade3d.myclass <- function(mesh, ...) {
  rgl:::shade3d.mesh3d(mesh, ..., lit = F)
}

shade3d(obj)

This now works. But I've read that using ::: to make use of hidden functions from another package is not good practice. Presumably it has been set as hidden for a reason. Do I have any other options here? Is this an acceptable use case for :::?


Solution

  • If you are just changing defaults, try NextMethod instead.

    # Creating a shade3d method for myclass
    shade3d.myclass <- function(mesh, ...) {
      NextMethod(mesh, ..., lit = FALSE)
    }
    

    Or even better, be user-friendly and set the defaults in the function definition.

    # Creating a shade3d method for myclass
    shade3d.myclass <- function(mesh, ..., lit = FALSE) {
      NextMethod(mesh, ..., lit = lit)
    }