Conditional formatting in backgroung on html in Rmarkdown

I have a html document in Rmarkdown. I am trying to conditional format the cells of a data frame called df .The condition is quite simple : if x< then background is grey and other wise pink background. But when I render it nothing happens .By "nothing" I mean no conditional formatting occures in the dara frame. Why ?

df <- tibble(variable = letters[1:6], 
             value1 = c(1:3, 5, 2, 4), 
             value2 = c(3:1, 4, 4, 2)) 

df


gc_cell_spec_row <- function(x){
  case_when( x<3  ~ kableExtra::cell_spec(x = x, format = "html", color = "white",background = "#BBBBBB"),
             x>=3 ~ kableExtra::cell_spec(x = x, format = "html", color = "white",background = "#F094F0")
  )
  return(x)
}


df%>%
  mutate(across(value1:value2, ~gc_cell_spec_row(.x)))%>%
  kableExtra::kbl(., "html", escape = FALSE)%>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"))


Hi @homerjaysimpson ,

I don't know what version of kableExtra you are using, but cell_spec is not encouraged anymore and the manual recommends column_spec instead.

This works for me

 
df <- tibble(variable = letters[1:6], 
             value1 = c(1:3, 5, 2, 4), 
             value2 = c(3:1, 4, 4, 2)) 

df$bg1 <- df$value1 <3
df$bg2 <- df$value2<3

df |>
    select(1:3) |>
  kbl() |>
  kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) |>
  column_spec(2, background = if_else(df$bg1, "red", "white")) |>
  column_spec(3, background = if_else(df$bg2, "red", "white"))

JW

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.