the*_*ist 4 modeling regression r formula nlme
我有一个gls模型,我将一个公式(从另一个对象)分配给模型:
equation <- as.formula(aic.obj[row,'model'])
> equation
temp.avg ~ I(year - 1950)
mod1 <- gls(equation, data = dat)
> mod1
Generalized least squares fit by maximum likelihood
Model: equation
Data: dat
Log-likelihood: -2109.276
Run Code Online (Sandbox Code Playgroud)
但是我不希望"模型"成为"方程式"而是"quation"本身!我该怎么做呢??
这是非常标准的,甚至lm会这样做.一种方法:劫持print.gls功能
library('nlme')
(form <- follicles ~ sin(2*pi*Time) + cos(2*pi*Time))
# follicles ~ sin(2 * pi * Time) + cos(2 * pi * Time)
(fm1 <- gls(form, Ovary))
# Generalized least squares fit by REML
# Model: form
# Data: Ovary
# Log-restricted-likelihood: -898.434
#
# Coefficients:
# (Intercept) sin(2 * pi * Time) cos(2 * pi * Time)
# 12.2155822 -3.3396116 -0.8697358
#
# Degrees of freedom: 308 total; 305 residual
# Residual standard error: 4.486121
print.gls <- function(x, ...) {
x$call$model <- get(as.character(x$call$model))
nlme:::print.gls(x, ...)
}
fm1
# Generalized least squares fit by REML
# Model: follicles ~ sin(2 * pi * Time) + cos(2 * pi * Time)
# Data: Ovary
# Log-restricted-likelihood: -898.434
#
# Coefficients:
# (Intercept) sin(2 * pi * Time) cos(2 * pi * Time)
# 12.2155822 -3.3396116 -0.8697358
#
# Degrees of freedom: 308 total; 305 residual
# Residual standard error: 4.486121
Run Code Online (Sandbox Code Playgroud)
你可以通过一些巧妙的语言修改来解决这个问题.这将创建(未gls评估的)调用,直接插入模型方程,然后对其进行求值.
cl <- substitute(gls(.equation, data=dat), list(.equation=equation))
mod1 <- eval(cl)
Run Code Online (Sandbox Code Playgroud)