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)

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

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


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) = - 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())
1 Like

@Christopher_Fisher thank you! This is solution.

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

1 Like