[R] First call to constructor fails (R.oo)

Henrik Bengtsson hb at stat.berkeley.edu
Wed Dec 10 19:19:09 CET 2008


Hi,

Any R.oo Object must accept no arguments, e.g. Object().  Thus, in
your case you need to be able to support the call MyClass().  The
reason is that the first time you use the class, R.oo will create a
static object of the class by calling <ClassName>().

Typically, I would do it this way:

setConstructorS3("MyClass",function(param=NULL) {
  print(param);
  extend(Object(),"MyClass", .param=param);
})

Hope this helps

Henrik

On Wed, Dec 10, 2008 at 9:59 AM, Valentin Ruano
<valentin.ruano at gmail.com> wrote:
> Hi all,
>
> I'm trying to do some object-oriented programming in R using the R.oo
> package.
>
> Right from the start I encountered a strange (at least for me) problem. I
> define a new class/constructor based on the R.oo documentation.
>
> However the first attempt to create an object fails:
>
> === Code: ===
>
> library(R.oo);
>
> setConstructorS3("MyClass",function(param) {
>    print(param);
>    extend(Object(),"MyClass", .param=param);
> })
>
> print("Attempt1");
> obj = MyClass(1);
>
> === Output: ===
>
> Loading required package: R.methodsS3
> R.methodsS3 v1.0.3 (2008-07-02) successfully loaded. See ?R.methodsS3 for
> help.
> R.oo v1.4.6 (2008-08-11) successfully loaded. See ?R.oo for help.
> [1] "Attempt1"
> [1] 1
> Error in print(param) : argument "param" is missing, with no default
>
> ===
>
>
> Yet a second attempt, within the same session, calling the same constructor
> with the same parameters works!
>
> === Code: ===
>
> print ("Attempt2");
> obj = MyClass(1);
> print(obj);
>
> === Output: ===
>
> [1] "Attempt2"
> [1] 1
> [1] "MyClass: 0x140154948"
>
> ====
>
> What I am doing wrong? Seems that the constructor definition does not come
> fully into effect before I call if for the first time (apparently too late)
>
> thanks in advance, V.
>
> === sessionInfo ===
>
> R version 2.6.2 (2008-02-08)
> i486-pc-linux-gnu
>
> locale:
> LC_CTYPE=en_IE.UTF-8;LC_NUMERIC=C;LC_TIME=en_IE.UTF-8;LC_COLLATE=en_IE.UTF-8;LC_MONETARY=en_IE.UTF-8;LC_MESSAGES=en_IE.UTF-8;LC_PAPER=en_IE.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_IE.UTF-8;LC_IDENTIFICATION=C
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> other attached packages:
> [1] R.oo_1.4.6        R.methodsS3_1.0.3
>
> loaded via a namespace (and not attached):
> [1] rcompgen_0.1-17 tcltk_2.6.2     tools_2.6.2
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list