[R] Ask if an object will respond to a function or method
Martin Morgan
martin.morgan at roswellpark.org
Thu Mar 31 22:30:57 CEST 2016
On 03/31/2016 04:00 PM, Paul Johnson wrote:
> In the rockchalk package, I want to provide functions for regression
> objects that are "well behaved." If an object responds to the methods
> that lm or glm objects can handle, like coef(), nobs(), and summary(),
> I want to be able to handle the same thing.
>
> It is more difficult than expected to ask a given fitted model object
> "do you respond to these functions: coef(), nobs(), summary()." How
> would you do it?
>
> I tried this with the methods() function but learned that all methods
> that a class can perform are not listed. I'll demonstrate with a
> regression "zz" that is created by the example in the plm package.
> The coef() function succeeds on the zz object, but coef is not listed
> in the list of methods that the function can carry out.
>
>> library(plm)
>> example(plm)
>
>> class(zz)
> [1] "plm" "panelmodel"
>> methods(class = "plm")
> [1] ercomp fixef has.intercept model.matrix
> [5] pFtest plmtest plot pmodel.response
> [9] pooltest predict residuals summary
> [13] vcovBK vcovDC vcovG vcovHC
> [17] vcovNW vcovSCC
> see '?methods' for accessing help and source code
>> methods(class = "panelmodel")
> [1] deviance df.residual fitted has.intercept index
> [6] nobs pbgtest pbsytest pcdtest pdim
> [11] pdwtest phtest print pwartest pwfdtest
> [16] pwtest residuals terms update vcov
> see '?methods' for accessing help and source code
>> coef(zz)
> log(pcap) log(pc) log(emp) unemp
> -0.026149654 0.292006925 0.768159473 -0.005297741
>
> I don't understand why coef(zz) succeeds but coef is not listed as a method.
coef(zz) finds stats:::coef.default, which happens to do the right thing
for zz but also 'works' (returns without an error) for things that don't
have coefficients, e.g., coef(data.frame()).
stats:::coef.default is
> stats:::coef.default
function (object, ...)
object$coefficients
Maybe fail on use, rather than trying to guess up-front that the object
is fully appropriate?
Martin Morgan
>
> Right now, I'm contemplating this:
>
> zz1 < - try(coef(zz))
> if (inherits(zz1, "try-error")) stop("Your model has no coef method")
>
> This seems like a bad workaround because I have to actually run the
> function in order to find out if the function exists. That might be
> time consuming for some summary() methods.
>
> pj
>
This email message may contain legally privileged and/or confidential information. If you are not the intended recipient(s), or the employee or agent responsible for the delivery of this message to the intended recipient(s), you are hereby notified that any disclosure, copying, distribution, or use of this email message is prohibited. If you have received this message in error, please notify the sender immediately by e-mail and delete this email message from your computer. Thank you.
More information about the R-help
mailing list