[R] What if there's nothing to dispatch on?
murdoch@dunc@n @end|ng |rom gm@||@com
Wed Sep 1 11:35:03 CEST 2021
On 31/08/2021 11:59 p.m., Rolf Turner wrote:
> I'm trying to build a pair of (S3) methods, a "formula" method and a
> "default" method. The methods have a "data" argument. If the variables
> in question cannot be found in "data" then they should be sought in
> the global environment.
> My problem is that the generic dispatches on its first argument, which
> may be a formula (in which case it of course dispatches to the formula
> method) or the first of the variables. If this variable exists in
> the global environment then all is well. But if it doesn't exist there,
> then the generic falls over with an error of the form "object 'x' not
> found" --- because there isn't anything to dispatch on.
> I'd *like* to be able to tell the generic that if "x" is not found then
> it should dispatch to the default method (which will, if the call is
> sensible, find "x" in "data").
> Is there any way to tell the generic to do this?
> Or is there any other way out of this dilemma? (Other than "Give up and
> go to the pub", which I cannot currently do since Auckland is in Level 4
> lockdown. :-) )
That design is probably not a good idea: what if one of the variables
in data matches the name of some other object in the global environment?
Then it would dispatch on that other object, and things won't go well.
But here's a way to shoot yourself in the foot:
x1 <- try(x, silent = TRUE)
if (inherits(x1, "try-error"))
More information about the R-help