'Markdown math formula from character string (RStudio knitr)

I have a character string variable (extracted from a regression model) that I would like to display as a math formula in a report using markdown in Rstudio knitr. For example

> formula
[1] "dGU ~ L(ec, 1) + dHH + L(dHH, 1) + L(dHH, 2) + L(dHH, 3) + dJKM + L(dJKM, 1) + L(dJKM, 2) + L(dJKM, 3) + L(dJKM, 4) + dTTF + L(dGU, 1) + L(dGU, 2) + L(dGU, 3) + L(dGU, 4) + L(dGU, 5) + L(dGU, 6) + L(dGU, 7) + L(dGU, 8) + L(dGU, 9) + L(dGU, 10) + L(dGU, 11) + L(dGU, 12) + L(dGU, 13) + L(dGU, 14) + L(dGU, 15)"
> 

I know I can always manually type a math formula using markdown, but I would like to use whatever character string variable is returned by the regression model programmatically.



Solution 1:[1]

How about something like this?

Put this in your code chunk first:

fml <- formula(dGU ~ L(ec, 1) + dHH + L(dHH, 1) + L(dHH, 2) + L(dHH, 3) + dJKM + L(dJKM, 1) + L(dJKM, 2) + L(dJKM, 3) + L(dJKM, 4) + dTTF + L(dGU, 1) + L(dGU, 2) + L(dGU, 3) + L(dGU, 4) + L(dGU, 5) + L(dGU, 6) + L(dGU, 7) + L(dGU, 8) + L(dGU, 9) + L(dGU, 10) + L(dGU, 11) + L(dGU, 12) + L(dGU, 13) + L(dGU, 14) + L(dGU, 15))


md_fml <- function(fml) { # make modifications to formula
  Reduce(paste, deparse(fml))
}

And call this in markdown after:

Here is my formula: **_`r md_fml(fml)`_**

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1