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

Ale*_*mbe 8 statistics r

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

lm(y ~ x, data=dat)
Run Code Online (Sandbox Code Playgroud)

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

是否存在从这样的公式转换为相应的公式的东西?在这种情况下,它可以写成:

y = B0 + B1*x
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*son 5

刚刚快速玩了一下并开始工作:

\n\n
# define a function to take a linear regression\n#  (anything that supports coef() and terms() should work)\nexpr.from.lm <- function (fit) {\n  # the terms we're interested in\n  con <- names(coef(fit))\n  # current expression (built from the inside out)\n  expr <- quote(epsilon)\n  # prepend expressions, working from the last symbol backwards\n  for (i in length(con):1) {\n    if (con[[i]] == '(Intercept)')\n        expr <- bquote(beta[.(i-1)] + .(expr))\n    else\n        expr <- bquote(beta[.(i-1)] * .(as.symbol(con[[i]])) + .(expr))\n  }\n  # add in response\n  expr <- bquote(.(terms(fit)[[2]]) == .(expr))\n  # convert to expression (for easy plotting)\n  as.expression(expr)\n}\n\n# generate and fit dummy data\ndf <- data.frame(iq=rnorm(10), sex=runif(10) < 0.5, weight=rnorm(10), height=rnorm(10))\nf <- lm(iq ~ sex + weight + height, df)\n# plot with our expression as the title\nplot(resid(f), main=expr.from.lm(f))\n
Run Code Online (Sandbox Code Playgroud)\n\n

似乎对变量的名称有很大的自由度,以及您是否真的想要其中的系数\xe2\x80\x94,但对于开始来说似乎很好。

\n