[R] Invalid term in model formula with gmm after formula.tools is loaded

Ivan Krylov |kry|ov @end|ng |rom d|@root@org
Fri Nov 1 22:29:45 CET 2024


Hi Aristide and welcome to R-help!

Your message was a bit mangled [*]. It's best to compose messages to
this mailing list in plain text. Otherwise (when composed in HTML), the
mailing list eats the HTML part and we're left with the plain text part
automatically generated by your mailer, which isn't always readable.

В Wed, 30 Oct 2024 17:45:29 +0100
Elysée Aristide <ariel92and using gmail.com> пишет:

> I am using the gmm function from the gmm package and encountered an
> unexpected error. No model can be estimated if I load formula.tools—I
> need to restart R each time.

I can reproduce the problem:

library(gmm)
data(Finance)
r <- Finance[1:300, 1:10]                                              
rm <- Finance[1:300, "rm"]                             
rf <- Finance[1:300, "rf"]
z <- as.matrix(r-rf) 
zm <- rm-rf
res <- gmm(z ~ zm, x = ~ zm)
library(formula.tools)
gmm(z ~ zm, x = ~ zm) # signals an error

Looking at the traceback(), I see the formula being transformed into NA
~ NA at some point:

10: terms.formula(formula, data = data) # <-- error happens here
9: terms(formula, data = data)
8: model.frame.default(data = object$data, formula = NA ~ NA, drop.unused.levels = TRUE, 
       na.action = "na.pass")
7: model.frame(data = object$data, formula = NA ~ NA, drop.unused.levels = TRUE, 
       na.action = "na.pass") # <-- formula is already NA ~ NA here
6: eval(mfh, parent.frame())
5: eval(mfh, parent.frame())
4: getDat(object$g, object$x, data = object$data)
3: getModel.baseGmm(all_args, ...)
2: getModel(all_args, ...)
1: gmm(z ~ zm, x = ~zm)

It seems that in base R, as.character(z ~ zm) returns a three-element
character vector, while with formula.tools loaded, it only returns a
single string, 'z ~ zm'. This breaks formula manipulation in getDat().

An immediate workaround is to replace the method provided by
formula.tools with one that immediately delegates back to R:

.S3method('as.character', 'formula', function (x, ...) NextMethod())
gmm(z ~ zm, x = ~ zm) # seems to work once again

(Is there a way to truly unregister an S3 method?)

Perhaps gmm::getDat could be made more robust by working directly on
the formula/call object instead of going through the string
representation.

-- 
Best regards,
Ivan

[*] https://stat.ethz.ch/pipermail/r-help/2024-October/480157.html



More information about the R-help mailing list