swaters swaters - 1 year ago 289
LaTeX Question

Conditional font color R Markdown

I am unable to find a way to include dynamic font colors in R Markdown based on the value of a variable (>0, ==0, or <0). Could anyone help? I tried an if statement where the return value is latex syntax, but that errored out. To be clear, I'm looking for PDF output. Here's what I tried:

```{r setup, include=FALSE}
x <- 4

This is an R Markdown document.
`r if (x>0) {\textcolor{red}{Markdown}} else if (x==0) {\textcolor{blue}{Markdown}} else {\textcolor{yellow}{Markdown}}`

In this dummy example, the font color should change based on the value of x (which I've set to 4).

Any help would be greatly appreciated!

Answer Source

I believe your issue is that the \t is interpretted as a tab character. Try escaping the \ like so:

`r if (x>0) "\\textcolor{red}{Markdown}" else if (x==0) "\\textcolor{blue}{Markdown}" else "\\textcolor{yellow}{Markdown}"`

That works when I run it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download