Home > OS >  Rmarkdown - if condition is true/false print table
Rmarkdown - if condition is true/false print table

Time:07-31

I am looking to conditionally display a table in a rmarkdown document. Some of the tables that are generated by my code may contain empty cells and I'm looking to exclude those tables and replace them with a message. Something like:

if_else(is.na(table[3,1]) == TRUE,"Data is currently not available",knitr::kable(table))

Is this possible?

CodePudding user response:

we create a TRUE/FALSE variable in a previous R chunk, then depending on a boolean operation, we get a value we can pass to the eval= R chunk options. In this example due to the result, we get a graph, instead of a table. Remember when naming R chunks, each one has to have a unique name.

---
title: "Untitled"
output: html_document
---

```{r setup, echo=FALSE, warning=FALSE, message=FALSE}
  if (iris$Sepal.Length[[1]] > 5)
     {show_text = TRUE
     } else {show_text = FALSE}

```

```{r conditional_block, eval=show_text, echo=FALSE}
head(iris, 5)
```

```{r setup2, echo=FALSE, warning=FALSE, message=FALSE}
  if (iris$Sepal.Length[[1]] < 5)
     {show_text = TRUE
     } else {show_text = FALSE}

```

```{r conditional_block2, eval=show_text, echo=FALSE}
plot(iris$Sepal.Length, iris$Sepal.Width)
```

enter image description here

  • Related