swaters swaters - 5 months ago 87
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!


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.