R Shiny: Conditional formatting selectInput items

拟墨画扇 提交于 2021-02-07 10:53:58

问题


When we have a all missing columns in the data frame, typically we don't want the user to select them to plot. There are many ways to do this but is it possible to let the items in the selectInput have conditional colors.

For example, how to let all missing column names (like the var2 column in my sample code) in the selectInput item list go grey. In other words, how to rewrite the selectInput for us to pass in a indicator vector for the conditional formatting.

library(shiny)

server <- function(input, session, output) {

  DATA = data.frame(var1 = c(2,3,4,1,5), var2 = c(NA,NA,NA,NA,NA))

  output$select_1 = renderUI({
    variables = names(DATA)
    selectInput("select_input","select", choices = variables)

    # is.all.na.indicator = sapply(DATA, function(x) all(is.na(x))) 
    # selectInput("select_input","select", choices = variables, goGrey = is.all.na.indicator)
  }) 
}

ui <- fluidPage(
    uiOutput("select_1")
)

shinyApp(ui = ui, server = server)

回答1:


library(shiny)

server <- function(input, session, output) {

  DATA <- data.frame(var1 = c(2,3,4,1,5), var2 = c(NA,NA,NA,NA,NA))

  output$select_1 <- renderUI({
    variables <- variableNames <- names(DATA)
    emptyColumns <- which(sapply(DATA, function(x) all(is.na(x))))
    for(i in emptyColumns){
      variableNames[i] <- 
        sprintf("<span style='color:red;'>%s</span>", variables[i])
    }
    selectizeInput("select_input", "select", 
                   choices = setNames(variables, variableNames), 
                   options = list(render = I("
  {
    item: function(item, escape) { return '<div>' + item.label + '</div>'; },
    option: function(item, escape) { return '<div>' + item.label + '</div>'; }
  }")))
  }) 
}

ui <- fluidPage(
  uiOutput("select_1")
)

shinyApp(ui = ui, server = server)



来源:https://stackoverflow.com/questions/42522429/r-shiny-conditional-formatting-selectinput-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!