我正在做混合模型,并且有4个变量x1-x4以及因变量y。该类变量称为cla。当前的建模结构是
md<-lmer(y~x1+x2+x3+x4+(1+x2|cla)+(1+x4|cla),data=mydata)
但是,假设我想将模型更改为以下格式
md<-lmer(y~x1+x2+x3+x4+(1+x2|cla)+(1+x3|cla)+(1+x4|cla),data=mydata)
我的问题是,如何使此代码动态化,以便我可以选择变量,并将其合并到模型中。对于仅4个变量,并不是很困难。但是对于大量变量,手动添加变量非常麻烦。
谢谢!
事先准备公式的各个部分,将它们粘合在一起,然后将其强制到一个formula
对象上。您可以将各个部分准备为其自己的变量,将它们命名为可预测的(x2
,x37,
x4 ) so that you can automatically find them using
ls(pattern =“”). You fetch each object using
get , pass that to
paste , use a
crash`参数,将它们粘合在一起,等等。
fixed.part <- "y ~ x1 + x2 + x3"
x2 <-"(1+x2|cla)"
x3 <- "(1+x3|cla)"
x4 <- "(1+x4|cla)"
random.part <- paste(sapply(ls(pattern = "^x"), get), collapse = " + ")
formula(paste(fixed.part, random.part, sep = " + "))
y ~ x1 + x2 + x3 + (1 + x2 | cla) + (1 + x3 | cla) + (1 + x4 | cla)
如果您希望减少手动控制,则可以构造一个“空白”随机零件,添加一个适当的数字,其余与上述相同。
x <- "(1+x%s|cla)"
random.part <- paste(sprintf(x, 1:10), collapse = " + ")
formula(paste(fixed.part, random.part, sep = " + "))
y ~ x1 + x2 + x3 + (1 + x1 | cla) + (1 + x2 | cla) + (1 + x3 |
cla) + (1 + x4 | cla) + (1 + x5 | cla) + (1 + x6 | cla) +
(1 + x7 | cla) + (1 + x8 | cla) + (1 + x9 | cla) + (1 + x10 |
cla)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句