9

当我们在 R 中拟合统计模型时,比如说

lm(y ~ x, data=dat)

我们使用 R 的特殊公式语法:“y~x”

有什么东西可以从这样的公式转换为相应的方程吗?在这种情况下,它可以写成:

y = B0 + B1*x

这将非常有用!一方面,因为对于更复杂的公式,我不相信我的翻译。其次,在使用 R/Sweave/knitr 撰写的科学论文中,有时模型应该以方程的形式报告,对于完全可重复的研究,我们希望以自动化的方式进行。

4

1 回答 1

4

刚玩了一会儿,就开始工作了:

# define a function to take a linear regression
#  (anything that supports coef() and terms() should work)
expr.from.lm <- function (fit) {
  # the terms we're interested in
  con <- names(coef(fit))
  # current expression (built from the inside out)
  expr <- quote(epsilon)
  # prepend expressions, working from the last symbol backwards
  for (i in length(con):1) {
    if (con[[i]] == '(Intercept)')
        expr <- bquote(beta[.(i-1)] + .(expr))
    else
        expr <- bquote(beta[.(i-1)] * .(as.symbol(con[[i]])) + .(expr))
  }
  # add in response
  expr <- bquote(.(terms(fit)[[2]]) == .(expr))
  # convert to expression (for easy plotting)
  as.expression(expr)
}

# generate and fit dummy data
df <- data.frame(iq=rnorm(10), sex=runif(10) < 0.5, weight=rnorm(10), height=rnorm(10))
f <- lm(iq ~ sex + weight + height, df)
# plot with our expression as the title
plot(resid(f), main=expr.from.lm(f))

似乎对于调用什么变量以及您是否真的想要其中的系数有很大的自由度 - 但似乎是一个很好的开始。

于 2013-11-07T12:27:10.143 回答