Skip to content

Instantly share code, notes, and snippets.

@johansigfrids
Created May 9, 2014 15:19
Show Gist options
  • Save johansigfrids/cb8530a4bb85cdc20957 to your computer and use it in GitHub Desktop.
Save johansigfrids/cb8530a4bb85cdc20957 to your computer and use it in GitHub Desktop.
A macro that turns a linear model (LmMod, produced by lm() in GLM.jl) into a function which takes a separate argument for each variable in the model.
macro predfunc(name, model)
emod = eval(model)
typeof(emod) == LmMod || error("Error: Wrong model type.")
coefs = coef(emod)
if typeof(emod.ff.rhs) == Symbol
xes = [:intercept, emod.ff.rhs]
elseif typeof(emod.ff.rhs) == Expr
xes = emod.ff.rhs.args
xes[1] = :intercept
else
error("Error: Can't make sense of formula $(emod.ff)")
end
length(coefs) == length(xes) || error("Error: Wrong number of variables in forumal $(emod.ff)")
sums = Any[:($(coefs[i]) * $(xes[i])) for i in 1:length(xes)]
sums[1].args[3] = 1.0
lhs = Expr(:call)
lhs.args = prepend!(sums, Any[:+])
rhs = Expr(:call)
push!(rhs.args, name)
for i in 2:length(xes)
push!(rhs.args, :($(xes[i])::Number))
end
ex = Expr(:(=))
ex.args = Any[rhs, lhs]
eval(ex)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment