使用 formattable 根据另一列的值为一列着色

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

使用 formattable 包,可以很容易地根据其自身的值为一列着色:

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

有没有一种方法可以根据列 mpg 中的值来为列 cyl 着色? 谢谢!!

参见 "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