[英]How to run a model for multiple variables(columns) in df with lmer
I have several variables(columns) in a df I want to run lmer (from lme4 package). 我在df中有几个变量(列)我想运行lmer(来自lme4包)。
Say I have a dataframe called df: 假设我有一个名为df的数据框:
par1 par2 resp1 resp2
plant1 rep1 3 8
plant2 rep2 5 2
...
I'm trying to write a function to do this, but having trouble passing arguments and using them in the function. 我正在尝试编写一个函数来执行此操作,但无法传递参数并在函数中使用它们。
model1 = function(df, varname){
library(lme4)
model1 = lmer(varname ~ + (1 | par1) + (1 | par2), data=df)
return(model1)
}
resp1model = model1(df, "resp1")
resp2model = model1(df, "resp2")
Can someone advise on the best way to do this? 有人可以建议最好的方法吗? Maybe a function isn't the answer?
也许一个功能不是答案? A loop?
一个循环? I should say the reason is that once I get the function working, I want the function to return other things from the model.. such as the AIC, BLUPs, etc..
我应该说原因是,一旦我使函数工作,我希望函数从模型中返回其他东西......比如AIC,BLUP等。
I did this way, may be even better 我这样做,可能会更好
varlist=names(df)[i:j] #define what vars you want
blups.models <- lapply(varlist, function(x) {
lmer(substitute(i ~ (1|par1)+(1|par2)+(1|par3), list(i = as.name(x))), data = df, na.action=na.exclude)
})
here you have the list of models for all vars you want 在这里,您有所需的所有变量的模型列表
Another way is to substitute your line: 另一种方法是替换你的行:
model1 = lmer(varname ~ + (1 | par1) + (1 | par2), data=df)
with 同
model1 = lmer(paste0(varname," ~ + (1 | par1) + (1 | par2)"), data=df)
This will pass the formula as a string, which lmer(...)
will coerce to a formula. 这会将公式作为字符串传递,
lmer(...)
将强制转换为公式。
这是另一种方法..似乎有点复杂..但我认为我会将其添加为完整性: R:在混合效果模型中分析多个响应(即因变量)(lme4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.