Search code examples
rr-markdownkable

Conditional title heading depending on output of code block R Markdown


I know this question has been asked before, but I'm still struggling to find an answer that works with my example. Basically, I have this code block that reads the number of rows of a dataframe. If there are any rows in the dataframe, it will output a table using kable(). If there are zero rows, no table is output.

When the table IS output, I would like to have a title heading above the table (just bolded text, i.e. "My Table"). When no table is output, I want no heading. How can I accomplish this? I've tried to use eval statements like print_option in the r setup block but no luck. Here's the stripped-down pseudo-code:

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    
    #Existing data frame my_df

   numRows <- nrow(my_df)

   if (numRows>0) {

       #Print table 
       my_df %>%
       arrange(my_field)%>%
       kable() %>%  kable_styling(bootstrap_options = "striped","condensed", font_size = 12)

   }


```

Solution

  • I made minimal changes to implement your code with the iris dataset and it works as you would like it to.

    No rows (and no header)

    ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    library(dplyr)
    library(kableExtra)
    
    #Existing data frame my_df
    my_df <- iris[NULL, ]
    numRows <- nrow(my_df)
    ```
    
    `r  if (numRows > 0) {"## This is your heading written in markdown"}`
    
    ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    if (numRows>0) {
      #Print table 
      my_df %>%
        arrange(Species) %>%
        kable() %>%
        kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
    }
    ```
    

    With data (and table header)

    ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    library(dplyr)
    library(kableExtra)
    
    #Existing data frame my_df
    my_df <- iris[1:10, ]
    numRows <- nrow(my_df)
    ```
    
    `r  if (numRows > 0) {"## This is your heading written in markdown"}`
    
    ```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    if (numRows>0) {
      #Print table 
      my_df %>%
        arrange(Species) %>%
        kable() %>%
        kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
    }
    ```