Add method for GLM.LinearModel: MethodError: no method found


I am trying to implement a method GLM’s linear model. Unfortunately, I can’t specify this type in the function.

using GLM, RDatasets

iris = dataset("datasets", "iris")

fit = lm(@formula(SepalLength ~ PetalWidth), iris)

function print_r2(fit::LinearModel)
    R2 = r2(fit)
    R2_Adj = adjr2(fit)
    println("The model's explanatory power (R2) is of $(round(R2, 2)) (Adj. R2 = $(round(R2_Adj, 2))).")

MethodError: no method matching print_r2(::StatsModels.DataFrameRegressionModel{GLM.LinearModel{GLM.LmResp{Array{Float64,1}},GLM.DensePredChol{Float64,Base.LinAlg.Cholesky{Float64,Array{Float64,2}}}},Array{Float64,2}})
Closest candidates are:
  print_r2(::GLM.LinearModel) at In[7]:9

What is wrong with it? Should I specify the whole big type (StatsModels.DataFrame…) ?


This is a duplicate of I have written the answer there. The short explanation of the problem is that type of fit is not subtype of GLM.LinearModel.

This is what the error message tries to tell you; i.e. that the type of fit does not match method signature. Actually in Julia you could even leave out type specification like this:

function print_r2(fit)

and you should be fine most of the time.


Thanks, and sorry for the duplicate!