Convert the format of the formula R to a mathematical equation

When we fit the statistical model into R, let's say

lm(y ~ x, data=dat) 

We use the special formula syntax: "y ~ x"

Is there something that can be converted from such a formula to the corresponding equation? In this case, it can be written as:

 y = B0 + B1*x 

That would be very helpful! Firstly, because with more complex formulas, I do not trust my translation. Secondly, in scientific articles written using R / Sweave / knitr, sometimes the model must be presented in the form of an equation and for fully reproducible studies, we would like to do this in an automatic way.

+6
source share
1 answer

I just quickly played and got this job:

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

It seems that you have a lot of freedom about which variables cause, and whether you really want the coefficients to be there, but it seems to be good for a start.

+2
source

Source: https://habr.com/ru/post/955853/


All Articles