Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set method initialize S4 class vs. using function

Tags:

r

s4

I now have the class construction working in two ways:

The first,

setMethod("initialize", signature(.Object = "BondCashFlows"),
                  function(.Object, x, y, ...){ 
                    do some things .Object@foo = array[,m]
                  } 

The second,

BondCashFlows <- function(){do some things new("BondCashFlows", ...)

So, my question is why do I even have to bother with the first since the second is much more of a user friendly way of creating the object BondCashFlows?

I understand that the first is method on a class but I am not sure why I have to do this

like image 568
no name Avatar asked Oct 26 '13 23:10

no name


1 Answers

One of the advantage of using S4 method over a simple R function , is that the method is strongly typed.

  1. 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.
  2. 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.
  3. 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.

like image 85
agstudy Avatar answered Nov 15 '22 05:11

agstudy