根据多个条件更改数据表行的颜色

Changing the color of the datatable rows based on multiple conditions

我有一个包含很多行的数据 table,为了方便起见,我只使用两列。 下面是数据中的两列table.

rawdata <- data.frame(
  id = c(1,1,2,2,2,3,3),
  time = c(45,92,30,100,79,199,248)
)

我想根据特定条件为 dt 的整行着色。

  1. 如果id=1,我应该可以申请 backgroundColor = styleInterval(c(30,50), c('#C6EFCE', '#FFEB9C','#FFC7CE'))

  2. 如果id=2,我应该可以申请 backgroundColor = styleInterval(c(45,90), c('#e60000, '#000000','#ffffff))

  3. 如果id=3,我应该可以申请 backgroundColor = styleInterval(c(x,y), c('a, 'b,'c))

请找到我当前的数据代码table

library(DT)
datatable(
  rawdata,
  rownames = FALSE,
  options=list(
    pageLength = 20,
    scrollX = TRUE, 
    dom = 'prlti',
    initComplete =JS(
      "function(settings, json) {",
      "$(this.api().table().header()).css({'font-size': '20px','background-color': '#000', 'color': '#fff'});",
      "}"),
    columnDefs = list(list(className = 'dt-center', targets ="_all")),autowidth=T)
) %>%
  formatStyle(
    colnames(rawdata)[1:NCOL(rawdata)],target = 'row',
    # color =styleInterval(c(30,35), c('black', 'black', 'black')),
    backgroundColor =styleInterval(c(48,120), c('#C6EFCE', '#FFEB9C','#FFC7CE'))

  ) %>%
  formatStyle(columns = c(1:NCOL(rawdata)),'font-size' = '25px',fontWeight = 'Bold')

在这种情况下,我会将您想要的颜色存储在table 本身的每一行中,然后使用styleEqual 来设置每一行的颜色。 (我们还想隐藏包含颜色的列。)

为每行添加一个包含您要显示的颜色的列:

library(dplyr)
rawdata <- data.frame(
  id = c(1,1,2,2,2,3,3),
  time = c(45,92,30,100,79,199,248)
) %>%
  mutate(row.color = case_when(id == 1 & time <= 30 ~ "#C6EFCE",
                               id == 1 & time <= 50 ~ "#FFEB9C",
                               id == 1 ~ "#FFC7CE",
                               id == 2 & time <= 45 ~ "#E60000",
                               id == 2 & time <= 90 ~ "#000000",
                               id == 2 ~ "#FFFFFF",
                               T ~ "#888888"))

(我为 id = 3 使用灰色,因为原始 post 省略了该条件下的实际颜色。)

使用 styleEqual 设置 time 列中的单元格颜色,并使用 columnDefs 隐藏具有颜色十六进制值的列:

library(DT)
datatable(
  rawdata,
  rownames = FALSE,
  options=list(
    pageLength = 20,
    scrollX = TRUE, 
    dom = 'prlti',
    initComplete =JS(
      "function(settings, json) {",
      "$(this.api().table().header()).css({'font-size': '20px', 'background-color': '#000', 'color': '#fff'});",
      "}"),
    columnDefs = list(list(className = 'dt-center', targets = "_all"),
                      list(targets = 2, visible = F)),
    autowidth = T)
) %>%
  formatStyle(
    c("time"), "row.color",
    backgroundColor = styleEqual(sort(unique(rawdata$row.color)), sort(unique(rawdata$row.color)))

  ) %>%
  formatStyle(columns = c(1:NCOL(rawdata)),'font-size' = '25px',fontWeight = 'Bold')

我们得到以下结果:

如果您想在黑色行中呈现白色文本,您可以使用 text.color 添加另一列,并使用 styleEqualcolor 选项。