Dealing with empty tables in Rmarkdown output

Hi Everyone,

In my RMarkdown report, I am outputting tables using kable(). Sometimes the tables are blank because after running a query, no data is found which fulfils the requirement. I still need to print the table. It's part of a report and needs to show all outputs even if there were none. Does anyone know a way round this? If it can't print the table, is there anything I could add which states 'No data found'?

kable(Extreme_Values, format = "html", caption = 'List of Extreme Values') %>%
  kable_styling(bootstrap_options = c('striped', 'hover', 'condensed'),
                full_width = F, 
                position = 'left',
                font_size = 10) %>% 
  column_spec(1, bold = T, border_right = T)

Error in xml_children(x)[[search]] : subscript out of bounds

I believe the problem stems from the column_spec not finding any rows in the first column. One possible solution is to create a function that checks the number of rows of the data being turned into a table, and add the styling accordingly.

```{r}
library(knitr)
library(kableExtra)
library(dplyr)

dat <- mtcars[0,]

make_table <- function(df) {
  # If there is no data, don't add the column_spec
  if(nrow(df)==0) {
    kable(df, format = "html", caption = 'List of Extreme Values') %>%
      kable_styling(bootstrap_options = c('striped', 'hover', 'condensed'),
                    full_width = F, 
                    position = 'left',
                    font_size = 10) 
  } else { # Otherwise do add the styling
    kable(df, format = "html", caption = 'List of Extreme Values') %>%
      kable_styling(bootstrap_options = c('striped', 'hover', 'condensed'),
                    full_width = F, 
                    position = 'left',
                    font_size = 10) %>% 
      column_spec(1, bold = T, border_right = T)
  }
}

make_table(df = dat)
```

```{r}
dat <- mtcars[1,]

make_table(dat)
```
1 Like

Thanks jdb, exactly what I needed :grinning:

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.