这里是一个例子。我创建了一个数据框,并使用它来创建用于可视化的数据表。如您所见,我的列名和第一列中的行指示A和B中的条件。我要做的是更改此数据表中特定单元格的背景颜色。如该链接(https://rstudio.github.io/DT/010-style.html)所述,很容易选择要更改的列。但是,如何指定要选择的行对我来说并不明显。
为了给您更多背景信息,我正在开发一个Shiny
应用程序,我想设计一个数据表,使我可以根据A
和B
的情况为单元格着色。例如,如果A is less than 1
和B 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")
)
答案 0 :(得分:2)
我不确定要回答的问题,但是如果您要更改单元格的行索引和列索引(这是我的理解)所给定的背景色,可以执行以下操作:
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))
)
)