Conditional font color R Markdown

2019-06-12 17:16发布

问题:

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!

回答1:

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.