Search code examples
htmlrr-markdownkable

RMarkdown - having the title (text heading before a table) be conditional


I have an R Markdown that is parameterized. Basically, I'm filtering a dataframe by a "case_id" field and outputting a table of those filtered results. I render the RMarkdown document in a loop that cycles through each unique case_id. For each case_id in an array, I check the dataframe, and if it exists, I output a filtered table showing results for that case_id. Working example here:

RMarkdown:

---
title: "My Title"
output: 
  html_document:
params:
   case: case

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


## My Table

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
data <- read.csv(text="case_id,event,group,start,end,color,line.color
                       3,event_1,Project,2020-06-15,2020-10-15,#ffffff,#FF0000
                       3,event_1,Meetings,2020-07-30,2020-07-30,#ffffff,#0000ff
                       5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                       5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                       5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                       9,event_1,Meetings,2017-01-15,2017-01-15,#ffffff,#FF0000")
data$case_id <- as.numeric(data$case_id)
if(any(params$case==data$case_id)) {
    
   #Filter PDMP by the selected case
    data.filtered <- data %>%
                        filter(params$case==case_id)
    
    data.filtered <- data.filtered %>%
      filter(!is.na(start)&!is.na(end))
    
    pdmp_numRows <- nrow(data.filtered)

    if (pdmp_numRows>0) { 

    #Print table of prescriptions
    data.filtered %>%
      arrange(start)%>%
      kable() %>%  kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
      
    }
    
 }


```

And here is the R script that renders it:

library(dplyr)
library(knitr)
library(rmarkdown)


#--------------------- Render RMarkdown Document ---------------------
case_array <- c(1:10)

render_data <- function(case) {
  # assuming the output format of input.Rmd is PDF
  rmarkdown::render(
    "C:/Temp/test_kable.Rmd",
    output_file = paste0('//my_directory/', 'test_cable_ex_',case, '.html'),
    params = list(case=case),
    envir = parent.frame()
  )
}

for (case in case_array) {
  render_data(case)
}

The tables are output as expected. The problem is that when no table is made (when rows of the filtered dataframe = 0 ), I don't want the table heading "My Table" to show up. I only want "My Table" to show up when the table exists.

This is what I want:

enter image description here

This is what I don't want:

enter image description here


Solution

  • You can do this by wrapping the table heading in appropriate if statements.

       ---
        title: "My Title"
        output: 
          html_document:
        params:
           case: case
        ---
    
        ```{r setup, include=FALSE}
        knitr::opts_chunk$set(echo = TRUE)
        ```
    
        ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
        data <- read.csv(text="case_id,event,group,start,end,color,line.color
                               3,event_1,Project,2020-06-15,2020-10-15,#ffffff,#FF0000
                               3,event_1,Meetings,2020-07-30,2020-07-30,#ffffff,#0000ff
                               5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                               5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                               5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
                               9,event_1,Meetings,2017-01-15,2017-01-15,#ffffff,#FF0000")
        data$case_id <- as.numeric(data$case_id)
        param_check <- any(params$case==data$case_id)
        if (param_check) {
            
           #Filter PDMP by the selected case
            data.filtered <- data %>%
                                filter(params$case==case_id)
            
            data.filtered <- data.filtered %>%
              filter(!is.na(start)&!is.na(end))
            
            pdmp_numRows <- nrow(data.filtered)
            
        }
        ```
    
        `r  if (param_check) { if (pdmp_numRows > 0) {"# My Table"} }`
    
        ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
        if(param_check) {    
          if (pdmp_numRows>0) { 
        
            #Print table of prescriptions
                data.filtered %>%
              arrange(start)%>%
              kable() %>%  kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
            
          }
          
        }
        
        
        ```