One of the advantage of using S4 method over a simple R function , is that the method is strongly typed.
- Having a signature is a guard that methods aren't exposed to types that doesn't meet their signature requirements. Otherwise it will throw an exception.
- It's often the case that you want to differentiate method behavior depending on the parameter type passed. Strong typing makes that very easy and simple.
- Strongly typed is more human readable ( even if in R this argument can be debated, The S4 syntax is not very intuitive specially for a beginner)
Here and example, where I define a simple function then I wrap it in a method
show.vector <- function(.object,name,...).object[,name]
## you should first define a generic to define
setGeneric("returnVector", function(.object,name,...)
standardGeneric("returnVector")
)
## the method here is just calling the showvector function.
## Note that the function argument types are explicitly defined.
setMethod("returnVector", signature(.object="data.frame", name="character"),
def = function(.object, name, ...) show.vector(.object,name,...),
valueClass = "data.frame"
)
Now if you test this :
show.vector(mtcars,'cyl') ## works
show.vector(mtcars,1:10) ## DANGER!!works but not the desired behavior
show.vector(mtcars,-1) ## DANGER!!works but not the desired behavior
comparing to the method call:
returnVector(mtcars,'cyl') ## works
returnVector(mtcars,1:10) ## SAFER throw an excpetion
returnVector(mtcars,-1) ## SAFER throw an excpetion
Hence, If you will expose your method to others, it is better to encapsulate them in a method.