将R公式格式转换为数学方程式

9
当我们在R中拟合统计模型时,例如:
lm(y ~ x, data=dat)

我们使用R语言特有的公式语法:“y〜x”。
是否存在一种将这种公式转换为相应方程的工具?在这种情况下,它可以写成:
y = B0 + B1*x

这将非常有用!首先,因为在更复杂的公式中,我不信任我的翻译。其次,在使用R/Sweave/knitr撰写的科学论文中,有时应该以方程式形式报告模型,为了完全可再现的研究,我们希望自动化地实现这一点。

这个问题似乎不适合讨论,因为它涉及到统计学。 - Metrics
1
可能是重复的问题:ggplot2:在图表上添加回归线方程和R2 - nograpes
不是重复的问题,因为那个问题只涉及特定的、最简单的线性公式。我的问题是关于R公式的一般性问题,包括更复杂的公式。 - Alex Holcombe
可能有一种方法可以编写一个函数,将 my.model <- lm(y ~ x); model.matrix(my.model) 转换为您想要的形式。但我不知道是否已经存在这样的函数。 - Mark Miller
3
你可以使用 sep=*collapse = " + ",将你拟合的模型 m 的参数名和值粘合在一起。你可以从 terms(m) 中获取响应变量的名称。但是仍然会有很多琐碎的细节需要处理,比如将所有出现的 "+ -" 改为 "- ",并从打印结果中删除文本上的 "(Intercept)"。我猜以前可能有人已经做过了,但我不知道是谁! - Josh O'Brien
显示剩余2条评论
1个回答

5

我刚试了一下,成功地做到了以下操作:

# 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))

看起来对于变量的命名有很大的自由度,以及你是否需要在其中包含系数,但作为一个开始似乎不错。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接