0

I have a R Markdown child-file, which should produce different output based on a R-condition .

My code (sorry it is not reproducible):

{r results='asis', echo = FALSE}
if (class(robject) == "character") {
  cat("**R object is empty!**")  # This text should appear in RED in the Output (HTML) file.
} else {
  cat("### Data columns\n")
  cat("\n")
  kable(robject)
  cat("\n")
}

What the code does:

If my robject is not a data.frame it is set to an empty string (robject <- ""). With this "trick" it is possible to if_else about robject.

In my R Markdown file it should be printed either "R object is empty!" or a summary of the dataset (which is a data.frame again). If the dataset is empty, the text should appear in RED!

Two questions:

  1. How to print the text in RED (or every other color) using the cat command as in the example above? (I tried text_spec from kableextra as mentioned here, I tried crayron-Package as well and I tried to enter html_tags with print/cat . Neither worked!)

  2. Maybe it is better to if else outside the R Chunk. Unfortunately this approach did not work either enter link description here

Thank you for any help.

If you need some further information, please ask me for it. Thanks!

Petr Matousu
  • 3,120
  • 1
  • 20
  • 32
  • What matters here is the way you will then view your markdown file, if it is in md syntax highlighting or as html output. If html, then you can go for html styling of red text. What exactly is the question - how to style in html or how to embed it in if-else? – Petr Matousu Jul 17 '20 at 12:22

1 Answers1

0

For HTML you can wrap the text in <span> and use CSS to set the color. If you need to do this more than a couple of times, you can wrap it up in a simple function.

```{r results='asis', echo = FALSE}

cat_color <- function(message, color = "black") cat(sprintf("<span style = \"color: %s;\">%s</span>\n\n", color, message))

robject <- "some text"

if (class(robject) == "character") {
  cat_color("**R object is empty!**" , "red")  # This text should appear in RED in the Output (HTML) file.
} else {
  cat("### Data columns\n")
  cat("\n")
  kable(robject)
  cat("\n")
}
```

enter image description here

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56