如何使用" |"在朱莉娅表达中给出混合模型的符号

时间:2017-11-20 21:45:41

标签: julia

我想以编程方式迭代一些因变量并使用MixedModels包创建一些公式,例如:

form = @formula(y ~ 1 + x1 + x2 + (1 + x1 + x2 | stuff))

理想情况下,我会为因变量设置一个符号数组,并迭代它们并创建不同类型的公式:

depvars = [:height, :weight]

for var in depvars
    my_formula = @formula(var ~ otherstuff + (1 + otherstuff | thing))
    lm_out = fit!(lmm(my_formula, data))
end

其中otherstuffthing会发生变化。如果我没有混合模型,那么我可能会做类似的事情:

depvars = [:height, :weight]
f1 = Expr(:call, :+, [:x1, :x2])
f2 = Expr(:call, :+, [:x3, :x4])

for var in depvars
    my_formula1 = Formula(var, f1)
    my_formula2 = Formula(var, f2)
    lm_out = lm(my_formula1, data)
    # and so on...
end

但我不确定我是否可以在表达式中表达(1 + x1 + x2 | stuff)部分。

这可能吗?

1 个答案:

答案 0 :(得分:2)

而不是直接使用@formula使用DataFrames.Formula并在引用的表达式中插值:

using MixedModels, DataFrames

depvars = [:height, :weight]
things = [:thing1, :thing2]
otherstuffs = [:other1, :other2]

for thing in things, otherstuff in otherstuffs
    for var in depvars
        my_formula = Formula(var, :( $otherstuff + (1 +$otherstuff | $thing)))
        @show my_formula
    end
end

给出:

my_formula = Formula: height ~ other1 + ((1 + other1) | thing1)
my_formula = Formula: weight ~ other1 + ((1 + other1) | thing1)
my_formula = Formula: height ~ other2 + ((1 + other2) | thing1)
my_formula = Formula: weight ~ other2 + ((1 + other2) | thing1)
my_formula = Formula: height ~ other1 + ((1 + other1) | thing2)
my_formula = Formula: weight ~ other1 + ((1 + other1) | thing2)
my_formula = Formula: height ~ other2 + ((1 + other2) | thing2)
my_formula = Formula: weight ~ other2 + ((1 + other2) | thing2)