On 01/04/2012 06:09 AM, Peder Bacher wrote:
Hi
Being able to do object oriented programming in R is really good. I
now started using the Reference Classes and really like it.
Though, I have one problem: I cannot find a way to update a method on
an existing object.
The flexibility that scripting gives (really needed for interactive
data analysis) is lost if everything have to be recalculated all the
time.
For example I would normally work something like this:
cl1<- setRefClass("cl1",
fields=list(x="data.frame"),
methods=list(
init=function(){"Read and process data"},
fitModel=function(){"Fit different kind of models and keep the
results in x and other fields"},
plotFit1=function(){"Plot the fit one way"},
plotFit2=function(){"Plot the fit in another way way"})
)
I would then initialize it and run the functions on it:
cl1Object<- cl1$new()
...
The problem then comes if I need to change something in one of the
methods, because I then have to run all the initialization and fitting
again, since the change is done to "cl1" and not "cl1Object", of
course.
The reference class documentation states that it is not possible since
this would give problems with inheritance etc. Is there a workaround
to this?
I wouldn't say that this is recommended, but as a workaround the default
'initialize' method works as a copy constructor so
cl1 <- setRefClass("cl1",
fields=list(x="data.frame"),
methods=list(
plotFit1=function(){"Plot the fit one way"})
)
cl1Object <- cl1$new(x=data.frame(y=1:2))
cl1_a <- setRefClass("cl1",
fields=list(x="data.frame"),
methods=list(
plotFit1=function(){"Plot the fit one way"},
plotFit2=function(){"Plot the fit in another way way"})
)
and then
> cl1_aObject <- cl1_a$new(cl1Object)
> cl1_aObject$x
y
1 1
2 2
> cl1_aObject$plotFit2
Class method definition for method plotFit2()
function ()
{
"Plot the fit in another way way"
}
<environment: 0x19974e0>
Martin
The very best
Peder
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
--
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109
Location: M1-B861
Telephone: 206 667-2793
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.