Variable Colour with the if condition

Hello,

I'm making Rmarkdown raport and I want to add in text some colour for variable that has to depend from the if statement. For instance:
variable name: var
pseudocode: if (var > 1) than print(r var) in green else print('r var') in red.
Output:
Raport in html with
green number = var if var > 1 else
red number = var if var <= 1

How do I do that?

Thanks for advice

As there is no colorize feature in markdown, you'll need to generate text that make the colorization depending on your output. See this chapter in the Rmarkdown cookbook:

Example for HTML:

---
title: "R Notebook"
output: html_document
---

```{r, include=FALSE}
color_if <- function(var) {
  color <- if (var > 1) "green" else "red"
  sprintf("<span style='color: %s;'>%s</span>", color, var)
}
```

A value less than 1 is `r color_if(0.5)`.

A value above 1 is `r color_if(2)`

2 Likes

Thank you very much!

1 Like

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.