Question

How to make simple generic functions without making it too complicated? I want to have something like this:

inputA <- function(a,b){
    return(structure(c(a=a,b=b), class= "inputclassA"))
}

inputB <- function(c,d){
  return(structure(c(c=c,d=d), class= "inputclassB"))
}  

mathstuff.inputclassA <- function(inp){
  print("inputtype: inputclassA")
  inp['a'] + inp['b']
}  

mathstuff.inputclassB <- function(inp){
  print("inputtype: inputclassB")
  inp['c'] - inp['d']
}

mystructure <- inputA(4,2)
mathstuff(mystructure) #should return 6

mystructure <- inputB(4,2)
mathstuff(mystructure) #should return 4

So far I solved it like this

classCheck<-function(obj,checkIs){
  return (attr(obj,"class") == checkIs)
}

But isn't there a better way?

Was it helpful?

Solution

Okay, got it.

This is the key. What a shame, I didn't realize, the "related" thread had the answer.

mathstuff <- function(x,...) UseMethod("mathstuff")

So this works wonderfully. Sorry, my bad.

inputA <- function(a,b){
  return(structure(c(a=a,b=b), class= "inputclassA"))
}

inputB <- function(c,d){
  return(structure(c(c=c,d=d), class= "inputclassB"))
}  

#make generic function
mathstuff <- function(x,...) UseMethod("mathstuff")

mathstuff.inputclassA <- function(inp){
  print("inputtype: inputclassA")
  inp['a'] + inp['b']
}  

mathstuff.inputclassB <- function(inp){
  print("inputtype: inputclassB")
  inp['c'] - inp['d']
}

mystructure <- inputA(4,2)
mathstuff(mystructure) 

mystructure <- inputB(4,2)
mathstuff(mystructure) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top