Conditionally display math formulas with variables in R Markdown

Viewed 201

I have a problem with rendering formulas with variables in R markdown. Here is the variables that I using (simple example):

```{r, include=FALSE}
series <- c(1, 2, 3, 4)
count <- leng(series)
sum <- sum(series)
sum2 <- sum(series^2)
sq_formula <- TRUE

My problem is to print in Rmd (output = Word) math expression with knitr like:

$$S = \frac{\sum{S}}{n} = \frac{`r sum`}{`r count`} = `r mean(series)`$$

if sq_formula is FALSE, otherwise it should be:

$$S = \frac{\sum{S^2}}{n} = \frac{`r sum2`}{`r count`} = `r sum2 / count`$$

There is a way to write formulas in R chunk and print it by condition, like:

```{r, include=FALSE}
formula1 <- '$$ \\overline{S} = \\frac{\\sum{S}}{n} = \\frac{\\sum{`r sum`}{`r count`}}$$'
formula2 <- '$$ \\overline{S} = \\frac{\\sum{S^2}}{n} = \\frac {\\sum{`r sum2`}}{`r count`}$$'


`r if (sq_formula <- TRUE) {formula1} else {formula2}`

but I can't insert the variables like r sum, r count inside the chunk. I also tried to handle the problem with sprintf function, but haven't found a way to insert the variables in strings in math notation. So I would be grateful for any help.

1 Answers

What is the problem with sprintf? Can't you do

formula1 <- sprintf(
  '$$ \\overline{S} = \\frac{\\sum{S}}{n} = \\frac{\\sum{%s}{%s}}$$',
  sum, count
)
Related