r - 如何根据其值更改 R Shiny 数据表单元格的单元格颜色?

标签 r html-table shiny

我正在尝试根据其值更改 R Shiny 数据表的单元格颜色。例如,我创建了以下应用程序:

# 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 框架和结果页面:

HTML code generated by R Shiny to display the first 6 lines of the iris dataset as a data table

first 6 lines of the iris dataset displayed as a data table in R Shiny

例如,假设我希望所有包含整数的单元格都涂成红色。有选择地,我只想为第 2 行第 2 列和第 5 行第 1 列的单元格着色,其中值分别为 3 和 5。这在 R Shiny 中可能吗?

我目前的解决方法是在服务器端设置单个单元格的类,然后用 CSS 为它们着色。但是,我找不到办法做到这一点。

最佳答案

这里有两个想法:

I want all cells containing integers to be colored red



(1) 使用 Javascript 标记整数:
library(DT)
df <- head(iris)
df %>% 
  datatable %>% 
  formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))

Selectively, I'd like to color only the cells at row 2 column 2 and row 5 column 1



(2) 使用隐藏值列标记单元格:
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 中抽象出来的,因为这似乎是一个数据表问题。此外,可能还有更好的选择。

关于r - 如何根据其值更改 R Shiny 数据表单元格的单元格颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49636423/

相关文章:

r - 在 R Shiny App 中呈现 R Markdown 文档时引用书目不起作用

r - 了解 Shiny 中的 react 函数

r - 在 R 中的表中添加一行,其中每一列的总和

r - XTS 尺寸限制

r - 在图例 ggplot2 周围画一个框

Javascript:如何搜索表上两列以上

javascript - 在搜索时过滤表行使 onClick 不起作用

asp.net - 删除打印网页中 gridview 之前的分页符

r - tidyr 枢轴更宽 : Duplicate issue

r - 调用父 Shiny 服务器中的 react 数据集的 Shiny 模块