如何使用Formattable和COLOR_TILE对表格元素进行有条件的着色?

人气:83 发布:2023-01-03 标签: colors function r conditional-formatting formattable

问题描述

我正在尝试设置一个带有彩色瓷砖的表,这些瓷砖根据每列的平均值有条件地着色。基本上,如果值低于平均值,瓷砖将是红色的,如果值高于平均值,则是绿色的。我在下面的函数中使用了一个简单的If Else语句。

我最终将使用"Formattable"程序包和该程序包中的COLOR_TILE函数。

我已尝试编写自己的函数来挑选颜色,但它仅成功地标记了数据框中的第一行。

#library(formattable) # not used in this example
green <- "#71CA97"
red <- "#ff7f7f"

col1 <- c(1.2, 4.2, 5.6, 7.1)
col2 <- c(5.0, 1.3, 10.3, 6.0)
col3 <- c(4.7, 6.3, 1.5, 6.3)
mydata <- data.frame(col1, col2, col3)

colorPicker <- function(x) {
     if(x <= 5) {return("red")}
     else {return("green")}
}

tile.colors <- lapply(c(mydata), colorPicker)
警告消息: 在IF(x<;=5){: 条件的长度>%1,将只使用第一个元素

"tile.Colors"返回正确的颜色,但仅用于第一行。

我最终会在Formatable函数中调用"tile.Colors",但目前我只是尝试让颜色选择函数正确。

有没有更有效的方法来完成这项任务?

推荐答案

我改编了this answer to another question与color_tile相关的函数,使此函数在调用时使瓷砖按照列平均值上色:

 color_tile_mean <- function (...) {
  formatter("span", style = function(x) {
    style(display = "block",
          padding = "0 4px", 
          `border-radius` = "4px", 
          `background-color` = ifelse(x < mean(x) , "lightpink", "lightgreen"))
  })}

我不知道如何让它接受自定义颜色,所以要更改它们,只需修改函数中的ifelse条件。在您的案例中:

library(formattable)

# Set custom colors
green <- "#71CA97"
red <- "#ff7f7f"

# Make example table
col1 <- c(1.2, 4.2, 5.6, 7.1)
col2 <- c(5.0, 1.3, 10.3, 6.0)
col3 <- c(4.7, 6.3, 1.5, 6.3)
mydata <- data.frame(col1, col2, col3)

# Define color_tile_mean function
 color_tile_mean <- function (...) {
  formatter("span", style = function(x) {
    style(display = "block",
          padding = "0 4px", 
          `border-radius` = "4px", 
          `background-color` = ifelse(x < mean(x) , red, green)) # Remember to change the colors!
  })}

# Use it just like color_tile but without colors
formattable(mydata, align=c("c", "c", "c"),list(
  col1=color_tile_mean(),
  col2=color_tile_mean(),
  col3=color_tile_mean()
  )
)

Result

我希望这是有用的!

16