Programmatically create formula

Hi,

I’m wanting to use this formula programatically:

f = @formula(var ~ A * B + (1 | id))

Here’s what the AI recommends, but it doesn’t seem to work:

varname = :y  # or Symbol("y")
f = @formula($(varname) ~ A * B + (1 | id))

Following previous topics here in discourse I also tried Term(:fname) but this doesn’t work either, I’m getting this error:

ERROR: MethodError: no method matching |(::Int64, ::StatsModels.Term)
The function `|` exists, but no method is defined for this combination of argument types.

Any suggestions will be greatly appreciated!

You may need to run

using MixedModels

before trying this. If I recall correctly the code to parse expressions like (1 | id) is in the MixedModels package, not the StatsModels package

And the MixedModels package does re-export the @formula macro. Thus you do not need to explicitly import the StatsModels namespace.

Thanks, but that doesn’t seem to be the issue.

Works for me (although you must use @eval @formula for substitution of a symbol).

julia> using MixedModels

julia> varname = :y
:y

julia> form = @eval @formula($(varname) ~ 1 + (1|id))
FormulaTerm
Response:
  y(unknown)
Predictors:
  1
  (id)->1 | id
1 Like

Thank you so much for this (and for your amazing contributions to academia)!