3

I have several variables(columns) in a df I want to run lmer (from lme4 package).
Say I have a dataframe called 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..

4

3 回答 3

4

我是这样做的,可能会更好

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)
})

在这里你有你想要的所有变量的模型列表

于 2014-03-02T23:19:20.523 回答
2

另一种方法是替换您的行:

model1 = lmer(varname ~ + (1 | par1) + (1 | par2), data=df)

model1 = lmer(paste0(varname," ~ + (1 | par1) + (1 | par2)"), data=df)

这会将公式作为字符串传递,这lmer(...)将强制转换为公式。

于 2014-03-02T23:31:23.017 回答
0

这是另一种方法..似乎有点复杂..但为了完整性我想添加它: R:在混合效应模型(lme4)中分析多个响应(即因变量)

于 2014-03-04T22:01:14.063 回答