如何根据其值更改R Shiny数据表的单元格的单元格颜色?
我试图根据其值更改R Shiny数据表的单元格的单元格颜色.例如,我创建了以下应用程序:
I am attempting to change the cell color of cells of an R Shiny data table dependent on their value. As an example, I've created the following app:
# ui.R
fluidPage(
# Outputting data table.
DT::dataTableOutput("table")
)
# server.R
library(DT)
data(iris)
function(input, output) {
# Rendering data table.
output$table <- DT::renderDataTable({
head(iris)
},
options = list(dom = "t",
ordering = FALSE))
}
以下是上述代码生成的HTML框架和结果页面:
And the following is the generated HTML skeleton and resultant page from the above code:
作为一个例子,可以说我希望所有包含整数的单元格都被染成红色.选择性地,我只希望仅对第2行第2列和第5行第1列的单元格进行着色,其中值分别为3和5.在R Shiny中有可能吗?
As an example, lets say that I want all cells containing integers to be colored red. Selectively, I'd like to color only the cells at row 2 column 2 and row 5 column 1 where the values are 3 and 5 respectively. Is this possible in R Shiny?
我目前的解决方法是在服务器端设置单个单元格的类,并在以后使用CSS为它们着色.但是,我找不到办法.
My current idea for a work around is to set the class of individual cells server-side and color them later with CSS. However, I can't find a way to do this.
这里有两个想法:
我希望所有包含整数的单元格都被染成红色
I want all cells containing integers to be colored red
(1)使用JavaScript标记整数:
(1) Mark integers using Javascript:
library(DT)
df <- head(iris)
df %>%
datatable %>%
formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))
有选择地,我只想给第2行第2列的单元格着色,然后 第5行第1列
Selectively, I'd like to color only the cells at row 2 column 2 and row 5 column 1
(2)使用隐藏值列标记单元格:
(2) Mark cells using hidden value columns:
m <- matrix(F, ncol = ncol(df)-1, nrow = nrow(df))
m[rbind(c(2,2),c(5,1))] <- TRUE
df %>%
cbind(m) %>%
datatable(
options=list(columnDefs = list(list(visible=FALSE, targets=1:4+ncol(df)))),
) %>%
formatStyle(
columns = 1:4,
valueColumns = 1:4+ncol(df),
color = styleEqual(c(1,0), c("red", "black"))
)
我正在从Shiny进行抽象,因为这似乎是一个数据表问题.另外,可能还有更好的选择.
I'm abstracting from Shiny, since this seems to be a datatable question. Also, there may be better options.