[R] R.oo error upon construction
Henrik Bengtsson
hb at biostat.ucsf.edu
Tue Aug 9 00:37:00 CEST 2011
Hi,
you can do something like:
setConstructorS3("Person", function(name, age) {
# Check for missing arguments, but allow for empty
# constructor calls, i.e. Person().
if (missing(name) && missing(age)) {
name <- NA;
age <- NA;
} else if (missing(name)) {
throw("Argument 'name' is missing.");
} else if (missing(age)) {
throw("Argument 'age' is missing.");
}
extend(Object(), "Person",
.name=name,
.age=age
)
})
/Henrik
On Tue, Aug 9, 2011 at 12:21 AM, Ben qant <ccquant at gmail.com> wrote:
> Hello,
>
> Using the R.oo package, how do I throw an error if a field is not present
> when the user of the class creates the object?
>
> Using the example in the R.oo package:
>
> setConstructorS3("Person", function(name, age) {
> if (missing(name)) name <- NA;
> if (missing(age)) age <- NA;
>
> extend(Object(), "Person",
> .name=name,
> .age=age
> )
> })
>
> [rest of class methods here...etc...]
>
> User types this with no issues because both age and name are there:
>
> p1 <- Person("Dalai Lama", 67)
>
> User types this and I want it to throw an error because the age field is
> missing:
>
> p1 <- Person("Dalai Lama")
>
> Link to the example I am drawing from:
> http://127.0.0.1:22346/library/R.oo/html/Object.html
>
> I know how to throw an error when a method is used. I want to throw an error
> when the object is created.
>
> I've tried print and cat statements in the Constructor section and after the
> extend statement.
>
> Thanks,
> Ben
>
> [[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