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:

function(x) {
  x1 <- try(x, silent = TRUE)
  if (inherits(x1, "try-error"))
    foo.default(x)
  else
    UseMethod("foo", x)
}

Happy shooting!

Duncan

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.

Reply via email to