问题
I have a gls
model in which I assign a formula (from another object) to the model:
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
However I do not want the "Model" to be "equation" but rather the quation itself! How do I do this??
回答1:
This is pretty standard, even lm
would do this. One approach: hijack the print.gls
function
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
回答2:
You can fix this up with some nifty use of language mangling. This creates the (unevaluated) gls
call with the model equation inserted directly, and then evaluates it.
cl <- substitute(gls(.equation, data=dat), list(.equation=equation))
mod1 <- eval(cl)
来源:https://stackoverflow.com/questions/35803899/r-fix-model-call-in-model-using-as-formula