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
One of the advantage of using S4 method over a simple R function , is that the method is strongly typed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With