![](/img/trans.png)
[英]How Can I Change Background Color of Row based on cell value in Datatable?
[英]How to color the background of a cell in datatable (DT package) in R with column and row names or indices?
這是一個例子。 我創建了一個數據框並使用它來創建用於可視化的數據表。 如您所見,我的列名和第一列的行表示 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")
)
我不確定得到這個問題,但如果你想改變由行索引和列索引給出的單元格的背景顏色(這就是我的理解),你可以這樣做:
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))
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.