【问题标题】:How to color the background of a cell in datatable (DT package) in R with column and row names or indices?如何使用列名和行名或索引为 R 中的数据表(DT 包)中的单元格的背景着色?
【发布时间】:2019-09-03 13:55:53
【问题描述】:

这是一个例子。我创建了一个数据框并使用它来创建一个数据表以进行可视化。如您所见,我的列名和第一列中的行表示 A 和 B 的条件。我要做的是更改此数据表中特定单元格的背景颜色。选择要更改的列很容易,如此链接 (https://rstudio.github.io/DT/010-style.html) 中所述。但是,对我来说如何指定要选择的行并不明显。

为了给你更多的背景信息,我正在开发一个Shiny 应用程序,我想设计一个数据表,允许我根据AB 的条件为单元格着色。例如,如果A is less than 1B is between 1 and 2,我希望能够从A is less than 1 列中选择第二个单元格。为了实现这一点,我需要知道如何指定行号或行名。目前,我只知道如何根据行中的内容指定行,如本例所示。

library(tibble)
library(DT)

dat <- tribble(
  ~`A/B`,                ~`A is less than 1`, ~`A is between 1 and 2`,  ~`A is larger than 2`,
  "B is less than 1",                    10,                      30,                     30,
  "B is between 1 and 2",                 20,                      10,                     30,
  "B is larger than 2",                   20,                      20,                     10
)


datatable(dat, filter = "none", rownames = FALSE, selection = "none",
          options = list(dom = 't', ordering = FALSE)) %>% 
  formatStyle(
  'A is less than 1',
   backgroundColor = styleEqual(20, "orange")
)

【问题讨论】:

  • 您可以添加额外的不可见列来根据条件创建样式。看看我的回答:stackoverflow.com/questions/46367017.
  • @GregordeCillia 谢谢。不久前我赞成你的答案,但我没有完全研究你的答案。我会试试这个,让你知道它是否有效。

标签: html r colors shiny dt


【解决方案1】:

我不确定问题,但是如果您想更改由其行索引和列索引给出的单元格的背景颜色(这就是我的理解),您可以这样做:

changeCellColor <- function(row, col){
  c(
    "function(row, data, num, index){",
    sprintf("  if(index == %d){", row-1),
    sprintf("    $('td:eq(' + %d + ')', row)", col),
    "    .css({'background-color': 'orange'});",
    "  }",
    "}"  
  )
}
datatable(dat, 
          options = list(
            dom = "t",
            rowCallback = JS(changeCellColor(1, 2))
          )
)

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2020-05-22
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2020-01-01
    • 2012-07-22
    相关资源
    最近更新 更多