How to get number of Terms in @formula?

How to get number of Terms in @formula? Is any API?

is a good way to do it?

function nterms(model)
        if isa(model.rhs, Term)
            p = 1
        else isa(model.rhs, Tuple)
            p = length(model.rhs)
        end
        p
end

Iā€™m assuming that you are using GLM.jl or a related package. Would the following work?

nterms(model) = length(coef(model))

Hello!

No, unfortunately not. This returns a number of coefficients, not Trems/factors. For example model responce ~ 1 + treatment have 2 effects(I want to get this): Intercept + treatment, but it can be many levels - length(coef(model))

I think I understand now. I was digging through the model object structure and found a field that seems to count the number of variables (IVs and DVs). I am wondering if this might be what you are looking for:

nterms(model) = model.mf.schema.schema.count - 1

This counts the number of IVs which correspond to factors (I think). Using the following example from the documentation, it returns 2:

using DataFrames, CategoricalArrays, GLM

dobson = DataFrame(Counts    = [18.,17,15,20,10,21,25,13,13],
                          Outcome   = categorical([1,2,3,1,2,3,1,2,3]),
                          Treatment = categorical([1,1,1,2,2,2,3,3,3]))
gm1 = fit(GeneralizedLinearModel, @formula(Counts ~ Outcome + Treatment), dobson, Poisson())
nterms(gm1)
1 Like

@Christopher_Fisher thank you! This is solution.

Actually I use nterms(model) = model.mf.schema.schema.count, because Intercept Term was added automatically.

1 Like