2

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!

Mark Peterson
  • 9,370
  • 2
  • 25
  • 48
swaters
  • 77
  • 3
  • 11
  • What happens if you put quotes around the parts you want output? To be clear: what behavior are you getting now? – Mark Peterson Oct 31 '16 at 14:48
  • Hello, have you checked the answer to this question http://stackoverflow.com/questions/29067541/rmarkdown-how-to-change-the-font-color ? – Romain Oct 31 '16 at 15:12

1 Answers1

2

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.

Mark Peterson
  • 9,370
  • 2
  • 25
  • 48
  • Mark, this worked beautifully. However, now the output is surrounded by curly braces. Any idea on how to avoid this? Removing the braces around the text ("Markdown" in the example) did not work - it removed the formatting for all but the first letter and still wrapped the output in braces. Thanks for your help! – swaters Oct 31 '16 at 15:59
  • Remove the braces before `\\textcolor` and after `{Markdown}` See edit. – Mark Peterson Oct 31 '16 at 16:02
  • Exactly what I was looking for. Thanks Mark. – swaters Oct 31 '16 at 16:05
  • Is there something still missing that leads to you not accepting the answer? – Mark Peterson Oct 31 '16 at 16:17
  • Sorry about that Mark, I thought I had already accepted the answer. This should be fixed now. One question as I play around with this...any idea how to get the variable output rather than text? For example, if I want to color the font for variable x when x <- 4, do you know how to get the colored output of 4 rather than "x"? – swaters Oct 31 '16 at 16:25
  • You will likely need to use `paste` to combine the variable with other text output. – Mark Peterson Oct 31 '16 at 16:30