Search code examples
rclassr-s4r-lavaanr-s3

Error in getMethod("summary", signature = "FitDiff")


I am comparing lavaan objects using semTools::compareFit. It is throwing a very strange error message.

I tried also the following reproducible example:

data("HolzingerSwineford1939",package="lavaan")
HS.modelA <- ' visual  =~ x1 + x2 + x3
              textual =~ x4 + x5 + x6
              speed   =~ x7 + x8 + x9'

HS.modelB<- ' visual  =~ x1 + x2
              textual =~ x4 + x5 + x6
              speed   =~ x7 + x8 + x9'
fit.A<- cfa(HS.modelA, data = HolzingerSwineford1939)
fit.B<- cfa(HS.modelB, data = HolzingerSwineford1939)
semTools::compareFit(fit.A,fit.B)

It returns:

Error in getMethod("summary", signature = "FitDiff") : no method found for function 'summary' and signature FitDiff

Also, as the code is inside a function, but I would like to see the output printed in the screen, I also included:

result<-semTools::compareFit(fit.A,fit.B)
semTools::saveFile(result, file="",what="summary", tableFormat=FALSE)

This returns

Length Class Mode

  1 FitDiff      S4

I see the mention in the first error message something related to summary and methods... I have some S3 summary methods, trying to formalize in a package for personal use... not sure if it is related... is it possible I have messed up something? It is happening in more than one project in a RStudio installation... I have the impression it worked before...

I appreciate any help.


Solution

  • I am reporting here how I circumvented the problem.

    The conclusion of what is happening here:

    This is really an issue with S3 methods messing up the S4 method dispatch.

    If I load showMethods(summary) before loading the semTools package, I get:

    Function "summary":
     <not an S4 generic function>)
    

    But if I load showMethods(summary) after loading it, I get:

    Function: summary (package base)
    object="ANY"
    object="FitDiff"
        (inherited from: object="ANY")
    object="lavaan"
    object="lavaanList"
    object="mle"
    

    So, the solution:

    Considering the FitDiff object structure, I created a summary.FitDiff (s3 method):

    summary.FitDiff<-function(object){
              print(object@nested)
              return(object@fit)
    }
    

    and this summary method is used with the FitDiff object:

    a<-semTools::compareFit(fit.A,fit.B)
    summary(a)
    

    This is not a perfect solution, the ideal solution should involve something with how to specify s3 methods without messing up all possible s4method, but I have not sufficient knowledge about s4 methods... It solved my problem for now...