首页 文章

如何更改R Shiny数据表的单元格的单元格颜色取决于它的值?

提问于
浏览
3

我试图根据它们的值改变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为它们着色 . 但是,我找不到办法做到这一点 .

2 回答

  • 2

    这有两个想法:

    我希望所有包含整数的单元格都是红色的

    (1)使用Javascript标记整数:

    library(DT)
    df <- head(iris)
    df %>% 
      datatable %>% 
      formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))
    

    有选择地,我只想为第2行第2列和第5行第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中抽象出来,因为这似乎是一个可数据化的问题 . 此外,可能有更好的选择 .

  • 2

    此页面包含一系列用于格式化DT数据表的提示:https://rstudio.github.io/DT/010-style.html

    对于您的具体问题,有一个函数 formatStyle ,它允许您根据表中的特定值设置美学:

    library(DT)
    options(DT.options = list(pageLength = 5))
    df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))
    
    # style V6 based on values of V6
    datatable(df) %>% formatStyle(
        'V6',
        backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
    )
    
    # style V1 based on values of V6
    datatable(df) %>% formatStyle(
        'V1', 'V6',
        backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
    )
    

相关问题