Search code examples
robjectmethodsr-s3

dollar suggestions method in S3


I'm making right now a R package and I have to chose between returning lists and an object with S3 attributes. The good thing, as for the lists, is that it's very easy to use for beginners, due to the dollar sign making all the elements easy to find. The bad thing, is that it removes direct inheritance (I'd like to return a ts object with some additional informations).

The alternative would be to set the dollar for my S3 class, like this example :

object <- 1
class(object) <- "MyClass"
attr(object,"MyAttribute") <- "This is a secret"

`$.MyClass` <- function(x,name) attr(object,name)

object$MyAttribute

However, I have 2 questions about this :

  • Where to set the dollar partial matching function for the user to see "MyAttribute" as a valid choice in rstudio ?
  • Besides, is that a fine practice to do so or should I keep on using simple lists

Thanks


Solution

  • I don’t think RStudio currently allows this kind of customisation. In other R terminals you could play with rcompgen to generate completions but IIRC RStudio does its own thing.

    That said, your question seems to be based on a false dichotomy:

    Besides, is that a fine practice to do so or should I keep on using simple lists

    You don’t need to choose either–or. In fact, it’s common to have lists with S3 classes, and it is not common to use attributes to store S3 information that are then accessed via $. Just make your class a list:

    object = structure(
        list(value = 1, MyAttribute = "This is a secret"),
        class = "MyClass"
    )
    
    object$MyAttribute