Julien Massardier
Julien Massardier

Reputation: 1466

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!!

Upvotes: 3

Views: 876

Answers (1)

Mike Lee
Mike Lee

Reputation: 144

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

Upvotes: 4

Related Questions