JuliaStats / GLM.jl

Generalized linear models in Julia

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How do I metaprogramming for `@formula`

takuizum opened this issue · comments

Hi.

I would like to create @formula by using julia's Metaprogramming Meta.parse.

using  GLM, Random, Distributions, DataFrames
# Prepare dummy data.
Random.seed!(1234)
X = rand(Poisson(10), 200)
scl = [minimum(X):1:maximum(X);]
freq = map(j -> count(i -> i == j, X), scl)
df = DataFrame(y = freq, x = scl)
# Run `glm` with `Meta.parse` at global environment.
glm(eval(Meta.parse("@formula(y ~ x+x^2)")), df, Poisson(), LogLink())

This code works well in global env. However,

function shorthand(df)
    fm = eval(Meta.parse("@formula(y ~ x+x^2)"))
    glm(fm, df, Poisson(), LogLink())
end
shorthand2(df)

using function, return errors below,

julia> shorthand2(df)
ERROR: MethodError: no method matching (::var"#63#64")(::Int64)
The applicable method may be too new: running in world age 26838, while current world is 26839.
Closest candidates are:
  #63(::Any) at none:0 (method too new to be called from this world context.)
Stacktrace:
  [...]

How do I handle @formula by using metaprogramming?
(Should I try other methods?)

Please use the Discourse forum for questions, and keep GitHub for bug reports. Thanks!