Search code examples
rconditional-statementstooltipkable

Using ifelse() conditionals to create cell_spec() tooltips in KableExtra


I would like to use a conditional to add specific tooltips to certain cells in Kable. I have tried the following in an example below:

col1 <- c("A", "A*","B**")
col2 <- c("A**", "B", "C")
col3 <- c("A*", "B*", "C*")
Test <- data.frame(col1,col2,col3)
Test

Test %>%
   mutate_at(vars("col1":"col3"), ~ cell_spec(
        ., "html",
        tooltip = ifelse(. =="A*"|.=="B*"|.=="C*"|.=="D*", "Satisfactory to 22\u00B0C",
                         ifelse(. == "A**"|.=="B**"|.=="C**"|.=="D**","Satisfactory to 48\u00B0C", )))) %>%
   kable(format = "html", escape = FALSE) %>%
    kable_styling(full_width = FALSE,
                   bootstrap_options = c("striped","responsive", "hover"))

I would like to add a the tooltip "Satisfactory to 22\u00B0C" to every observation with one asterisk (e.g. A*, B*, C*), and "Satisfactory to 48\u00B0C" to every observation with two asterisks (A**, B**, C**). I would also like to leave the other data alone. Currently, I can only get this to work if I include a tooltip for all of the FALSE observations at the end of the ifelse statement. I tried setting the "else" arguement to NULL, but this did not work. Any help would be greatly appreciated, as I am very rusty when it comes to conditionals.


Solution

  • Sure, you can just use an empty string ""

    library(kableExtra, include.only = NULL)
    library(dplyr, include.only = "%>%")
    
    col1 <- c("A", "A*","B**")
    col2 <- c("A**", "B", "C")
    col3 <- c("A*", "B*", "C*")
    Test <- data.frame(col1,col2,col3)
    Test
    #>   col1 col2 col3
    #> 1    A  A**   A*
    #> 2   A*    B   B*
    #> 3  B**    C   C*
    
    Test %>%
      dplyr::mutate_at(
        .vars = dplyr::vars("col1":"col3"),
        .funs = ~kableExtra::cell_spec(
          x = .,
          format = "html",
          tooltip = ifelse(test = . =="A*"|.=="B*"|.=="C*"|.=="D*",
                           yes  = "Satisfactory to 22\u00B0C",
                           no   = ifelse(test = . == "A**"|.=="B**"|.=="C**"|.=="D**",
                                         yes  = "Satisfactory to 48\u00B0C", 
                                         no   = "")))) %>%
      kableExtra::kable(format = "html", escape = FALSE) %>%
      kableExtra::kable_styling(full_width = FALSE,
                                bootstrap_options = c("striped","responsive", "hover"))