1
votes

I am trying to build an app in shiny that will be able to load a dataset in the server function and then based on the user choose and then if there is a factor variable to open check box using conditionalPanel. is there a way to output variable from the server as the condition of the condtionalPanel?

Here is what I tried:

library(shiny)
library(caret)

ui <- fluidPage(
  selectInput('dataset', 'Select Dataset', 
              list(GermanCredit = "GermanCredit",
                  cars = "cars")),

  conditionalPanel(
    condition = "output.factorflag == true",
    checkboxInput("UseFactor", "Add Factor Variable")
  ) 
)


server <- function(input, output) {
  # Loading the dataset
  df <- reactive({
    if(input$dataset == "GermanCredit"){
      data("GermanCredit")
      df <- GermanCredit
    }else if(input$dataset == "cars"){
      data(cars)
      df <- cars
    }

    return(df)
  })

  # Loading the variables list
  col_type <- reactive({
    col_type <- rep(NA,ncol(df()))
    for(i in 1:ncol(df())){
      col_type[i] <- class(df()[,i])
    }
    return(col_type)
  }) 

  outputOptions(output, "factorflag", suspendWhenHidden = FALSE)


  output$factorflag <- reactive({
    if("factor" %in% col_type()){
      factor.flag <- TRUE
    } else {factor.flag <- FALSE}
  }
  )
}


shinyApp(ui = ui, server = server)

Thank you in advance!
1

1 Answers

3
votes

You were almost there, you need to put the outputOptions after the declaration of factorflag. Just reengineered a bit your code:

library(shiny)
library(caret)

ui <- fluidPage(
  selectInput('dataset', 'Select Dataset', 
              list(GermanCredit = "GermanCredit",
                   cars = "cars")),

  conditionalPanel(
    condition = "output.factorflag == true",
    checkboxInput("UseFactor", "Add Factor Variable")
  ) 
)


server <- function(input, output) {
  # Loading the dataset
  df <- reactive({
    if(input$dataset == "GermanCredit"){
      data("GermanCredit")
      GermanCredit
    }else {
      data("cars")
      cars
    }
  })
  output$factorflag <- reactive("factor" %in% sapply(df(),class))
  outputOptions(output, "factorflag", suspendWhenHidden = FALSE)
}

shinyApp(ui = ui, server = server)