Search code examples
rr-markdownkablekableextra

how to combine R ifelse() and kable()


I have R Markdown scripts I run periodically which contain conditional tables with what I'll call violators. Here's an example data frame:

df <- data.frame(Person = c("Jack", "Jill"), Violator = c("F", "F"))

#>   Person Violator
#> 1   Jack        F
#> 2   Jill        F

I only want to show violators (Violator == "T") and there aren't any this month. So my 'normal' kable code below gives me this error, "subscript out of bounds" which I'd expect.

How can I modify my kable code to 'do nothing' if violator does not equal "T". Is ifelse() the way to go? I'm open to kableExtra() solutions.

kable(df %>% filter(Violator == "T"), "html", align = "l") %>%
  kable_styling("striped", "hover", full_width = F) %>%
  column_spec(1, bold = T, background = "#FFFFFF") %>%
  collapse_rows(columns = 1)

Solution

  • This simple approach should work, I think:

    ```{r}
    temp <- df %>% filter(Violator == "T")
    
    if(nrow(temp) != 0){
    kable(temp, "html", align = "l") %>%
      kable_styling("striped", "hover", full_width = F) %>%
      column_spec(1, bold = T, background = "#FFFFFF") %>%
      collapse_rows(columns = 1)
    }
    ```