R:使用 as.formula 修复模型中的模型调用

标签 r formula regression modeling 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

然而 我不希望“模型”是“方程”,而是方程本身!我该怎么做呢??

最佳答案

这是非常标准的,甚至 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 

关于R:使用 as.formula 修复模型中的模型调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803899/

相关文章:

r - 在melt/gather 中为新列指定类

R - ggplot - geom_bar 的圆形末端

r - 循环 r 中的字符串

java - 带有公式的 Hibernate @OneToOne - 列不能外部连接到子查询

r - 使用 qplot 的多层平滑图

string - 在 R 中使用字符串名称分配 data.frame 的列

google-sheets - 如何从具有不同特征的单元格中提取文本

c - 在 C 中实现求和公式

r - 用相同的设计矩阵拟合 R 中的许多线性模型

python - 如何将多项式回归线拟合到数据