Shiny中为DT表格行添加自定义背景色的语法问题求助
正确实现方案
原有写法错误点
callback是datatable()的独立顶层参数,不能放在options列表内,也不能单独赋值后接管道符formatStyle需要通过管道符直接衔接在datatable()对象后,才能正确作用于表格实例- 补充说明:如果需要按行号设置背景色,DT中行索引默认从0开始对应第一行,示例代码保持你原本「value为3的行设为红色」的需求。
完整可运行修正代码
library(shiny) library(DT) c1 = "This is comment 1" c2 = "This is comment 2" c3 = "This is comment 3" c4 = "This is comment 4" c5 = "This is comment 5" comments1 = list(c1,c2,c3,c4,c5) m1 = matrix( as.character(1:5), nrow = 5, ncol = 1, byrow = FALSE, dimnames = list(comments1, LETTERS[1]) ) for (i in seq_len(ncol(m1))) { m1[, i] = sprintf( '<input type="radio" name="%s" value="%s"/>', 'AValue', m1[,i] ) } callback1 <- c( "var LETTERS = ['AValue'];", "for(var i=0; i < LETTERS.length; ++i){", " var L = LETTERS[i];", " $('input[name=' + L + ']').on('click', function(){", " var name = $(this).attr('name');", " var value = $('input[name=' + name + ']:checked').val();", " Shiny.setInputValue(name, value);", " });", "}" ) ui <- fluidPage( title = 'Radio buttons in a table', DT::dataTableOutput('foo1'), verbatimTextOutput('sel1'), ) server <- function(input, output, session) { # 核心修正部分 output$foo1 = DT::renderDataTable({ datatable(m1, escape = FALSE, selection = 'none', server = FALSE, options = list(dom = 't', paging = FALSE, ordering = FALSE), callback = JS(callback1)) %>% # 按单选按钮value值匹配,值为3的行背景设为红色 formatStyle(0, target = 'row', backgroundColor = styleEqual(levels = "3", values = "red")) }) output$sel1 = renderPrint({ input[["AValue"]] }) } shinyApp(ui, server)
如果需要给多行设置不同背景色,直接给styleEqual传向量即可,比如styleEqual(levels = c("1","3","5"), values = c("blue","red","green"))就能分别给第1、3、5行设置对应颜色。
内容的提问来源于stack exchange,提问作者othnin
相关产品推荐
相关产品推荐

