The set method initializes the S4 class against using the function

Now I have a class that works in two ways:

The first,

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

Second,

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

So my question is, why do I even have to worry about the first, since the second is a much more convenient way to create a BondCashFlows object?

I understand the first method in the class, but I'm not sure why I should do this

+4
source share
1 answer

One of the advantages of using the S4 method over the simple function R is that the method is strongly typed .

  • Having a signature is a protection that methods are not exposed to types that do not meet their signature requirements. Otherwise, an exception.
  • , . .
  • ( R , S4 )

, ,

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"
)

, :

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 

:

returnVector(mtcars,'cyl')  ## works
returnVector(mtcars,1:10)   ## SAFER throw an excpetion
returnVector(mtcars,-1)     ## SAFER throw an excpetion

, , .

+9

All Articles