如何使用alternate()从nlme包中循环lme函数? [英] How to use substitute() to loop lme functions from nlme package?

查看:104
本文介绍了如何使用alternate()从nlme包中循环lme函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 lapply 循环中的 nlme 包中的> lme 函数.这适用于lmer 函数.rel ="nofollow noreferrer"> lme4 包,但会为 lme 生成错误消息.在下面的示例中,如何循环 lme 函数类似于 lmer 函数?

I am trying to use lme function from nlme package inside a lapply loop. This works for lmer function from lme4 package, but produces an error message for lme. How can I loop lme functions similarly to the lmer function in the example below?

library("nlme")
library("lme4")

set.seed(1)
dt <- data.frame(Resp1 = rnorm(100, 50, 23), Resp2 = rnorm(100, 80, 15), Pred = rnorm(100,10,2), group = factor(rep(LETTERS[1:10], each = 10)))

## Syntax:
lmer(Resp1 ~ Pred + (1 |group), data = dt)
lme(Resp1 ~ Pred, random = ~1 | group, data = dt)

## Works for lme4
lapply(c("Resp1", "Resp2"), function(k) {
  lmer(substitute(j ~ Pred + (1 | group), list(j = as.name(k))), data = dt)})

## Does not work for nlme
lapply(c("Resp1", "Resp2"), function(k) {
lme(substitute(j ~ Pred, list(j = as.name(k))), random = ~1 | group, data = dt)})

# Error in UseMethod("lme") : 
# no applicable method for 'lme' applied to an object of class "call"

PS.我知道此解决方案存在,但我想使用一种方法直接在响应变量中替换响应变量模型功能,而不是使用附加功能对数据进行子集设置.

PS. I am aware that this solution exists, but I would like to use a method substituting response variable directly in the model function instead of subsetting data using an additional function.

推荐答案

您也可以执行以下操作来代替摆弄 substitute eval :

Instead of fiddling around with substitute and eval you also could do the following:

lapply(c("Resp1", "Resp2"), function(r) {
   f <- formula(paste(r, "Pred", sep = "~"))
   m <- lme(fixed = f, random = ~ 1 | group, data = dt)
   m$call$fixed <- f
   m})

如果要为建模功能提供不同的数据集,则可以使用相同的技巧:

You could use the same trick if you want to provide different data sets to a modelling function:

makeModel <- function(dat) {
   l <- lme(Resp1 ~ Pred, random = ~ 1 | group, data = dat)
   l$call$data <- as.symbol(deparse(substitute(dat)))
   l
}

当我想从函数内部生成模型并随后进行更新时,我会使用此代码段很多.

I use this snippet quite a bit, when I want to generate a model from within a function and want to update it afterwards.

这篇关于如何使用alternate()从nlme包中循环lme函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆