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)
```