Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: fix model call in model using as.formula

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??

like image 919
theforestecologist Avatar asked Dec 25 '22 08:12

theforestecologist


1 Answers

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 
like image 118
rawr Avatar answered Dec 28 '22 08:12

rawr