我正在使用DT库中的数据表来获取来自我的Shinyapp的用户输入。 现在我想根据用户输入为数据表单元格的背景着色。
以下是我到目前为止的代码:
library(shiny)
library(data.table)
library(DT)
shinyApp(
ui = fluidPage(
title = 'Radio buttons in a table',
DT::dataTableOutput('foo'),
verbatimTextOutput('sel'), verbatimTextOutput('x2')
),
server = function(input, output, session) {
x <- data.table( 'Breed Split' = paste0("F",rep(0:16)), Friesian = rep(1,17), Cross = rep(2,17), Jersey = rep(3,17) ,
checked=c(rep("Friesian",9),rep("Cross",5),rep("Jersey",3))
)
x[, Friesian := sprintf( '<input type="radio" name="%s" value="%s" %s/>', `Breed Split`, x[, Friesian],ifelse("Friesian"==x[, checked],"checked" ,""))]
x[, Cross := sprintf( '<input type="radio" name="%s" value="%s" %s/>', `Breed Split`, x[, Cross],ifelse("Cross"==x[, checked],"checked" ,"" ))]
x[, Jersey := sprintf( '<input type="radio" name="%s" value="%s" %s/>', `Breed Split`, x[, Jersey] ,ifelse("Jersey"==x[, checked],"checked" ,""))]
output$foo = DT::renderDataTable(
x[,-c("checked")], escape = FALSE, selection = 'none', server = FALSE, rownames=FALSE,
options = list(dom = 't', paging = FALSE, ordering = FALSE),
callback = JS("table.rows().every(function(i, tab, row) {
var $this = $(this.node());
$this.attr('id', this.data()[0]);
$this.addClass('shiny-input-radiogroup');
});
Shiny.unbindAll(table.table().node());
Shiny.bindAll(table.table().node());")
)
output$sel = renderPrint({ sapply(x$`Breed Split`, function(i) input[[i]]) })
}
)
所选品种的细胞背景颜色:
弗里斯:红色
十字架:绿色
泽西岛:蓝色
换句话说,我需要在formatStyle()
DT::renderDataTable
答案 0 :(得分:1)
我创建了一个小例子,其中所选单元格的背景颜色根据用户输入而变化。我希望这有帮助!
server.R
library(shiny)
library(DT)
shinyServer(function(input, output, session) {
dataReactive <- reactive({
return(mtcars[mtcars$gear==input$gear,])
})
output$table1 <- DT::renderDataTable({
df <- head(mtcars,100)
if(input$gear==1) color="red"
if(input$gear==2) color="blue"
if(input$gear==3) color="green"
if(input$gear==4) color="lightblue"
DT::datatable(df) %>% formatStyle(c("mpg", "cyl", "disp"),
backgroundColor = color)
})
})
ui.R
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("gear","Select gear:", choices = c(1,2,3,4))
),
mainPanel(
DT::dataTableOutput("table1")
)
)
))