Search code examples
rformattable

color a column based on the values of another column with formattable


With the formattable package, it's easy to color one column based on its own values:

formattable::formattable(mtcars[1:3,1:2],list(mpg=color_text("blue","red")))

enter image description here

Is there a way to color the column cyl based on the values in the column mpg instead? Thanks!!


Solution

  • See second argument under "list":

    library(formattable)
    
    formattable::formattable(mtcars[1:3,1:2], 
                         list(mpg = color_text("blue","red"),
                              cyl = formatter("span",
                                              style = x ~ style(color = ifelse(mtcars$mpg[1:3] == 21, "blue", "red")))))
    

    "...we define x as being the value by placing it to the left of the ~ and then use it in the function to the right (it is a lambda function, to use some jargon)" read more here