首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R:使用as.formula修复模型调用

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

Stack Overflow用户
提问于 2016-03-04 18:54:18
回答 2查看 534关注 0票数 4

我有一个gls模型,在该模型中,我为模型分配了一个公式(来自另一个对象):

代码语言:javascript
复制
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

,但是,,我不希望“模型”成为“等式”,而希望它本身就是“方程”!我该怎么做??

EN

回答 2

Stack Overflow用户

发布于 2016-03-04 19:12:18

这是非常标准的,就连lm也会这么做。一种方法:劫持print.gls函数

代码语言:javascript
复制
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 
票数 5
EN

Stack Overflow用户

发布于 2016-03-04 19:28:50

你可以用一些巧妙的语言破坏来解决这个问题。这将使用直接插入的模型方程创建(未评估的) gls调用,然后计算它。

代码语言:javascript
复制
cl <- substitute(gls(.equation, data=dat), list(.equation=equation))
mod1 <- eval(cl)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35803899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档