Search code examples
rfunctionclasspaste

Make class() more flexible with function


I have this function called Dude. it takes Data as a required NanoStringGeoMxSet class, with Norm being "neg" input. I want to through a flag/error for user if class isnt correct. However, Data = (can be any labeled input). I want to allow class to take in this any variable to check class status. Any thoughts?

Dude <- function(Data, Norm) {
  
  if(class(data)[1] != "NanoStringGeoMxSet"){
    stop(paste0("Error: You have the wrong data class, must be NanoStringGeoMxSet" ))
  }

  ## rest of code
}

Dude(Data = data, Norm = "neg")

Solution

  • To start the discussion about an S3 implementation, here's a start:

    Dude <- function(Data, Norm) UseMethod("Dude")
    Dude.NanoStringGeoMxSet <- function(Data, Norm) {
      ## rest of code
    }
    
    Dude(mtcars)
    # Error in UseMethod("Dude") : 
    #   no applicable method for 'Dude' applied to an object of class "data.frame"
    

    If you want to customize the error message, or perhaps recover based on some other criteria, then you can define a "default" method along with the two above:

    Dude.default <- function(Data, Norm) {
      stop(paste("unrecognized class:",
           paste(sQuote(class(Data), FALSE), collapse = ", ")))
    }
    
    Dude(mtcars)
    # Error in Dude.default(mtcars) : unrecognized class: 'data.frame'
    

    FYI, if you want dispatch based on the second (and potentially subsequent) argument as well, you may want to consider R6 instead of S3. Its implementation is a lot more complex than this, but it better implements object-oriented and multi-argument dispatch, and adds public/private members/properties (among other differences). See https://r6.r-lib.org if you're at all interested.