Home > Software engineering >  R shiny: how to set selectInput that depends on the updateVarSelectInput()
R shiny: how to set selectInput that depends on the updateVarSelectInput()

Time:02-25

I want to upload a dataframe in shiny. Shiny will first read its colnames, and gives the option for users to select column, then with this selected column, users can select the levels in this column, which can be used as input for further analysis.

It is very similar as this example, but the selected values are output, which I cannot use for downstream analysis.

library(shiny)
myDF <- data.frame(A = 1:4, B = 3:6, C = 6:9, D = 10:13)
runApp(
  list(
    ui = fluidPage(
      uiOutput("myList"),
      uiOutput("myNumbers")
      )
    , server = function(input, output, session){
      output$myList <- renderUI({
        selectInput("compName", "Company Name:", LETTERS[1:4])
      })

      output$myNumbers <- renderUI({
        selectInput("compNo", "Product Line:", myDF[, input$compName])
      })
    }
    )
  )

my phsudo code is like this:

library(shiny)
runApp(
  list(
    ui = fluidPage(
      fileInput(inputId = "rawFile"), # Read the dataframe
      varSelectInput(inputId = "getColumn",
                     data = ""),
      selectInput(inputId = "levels",
                  choices = "")
    )
    , server = function(input, output, session){
      
      df <- reactive({
        inFile <- input$rawFile
        if (is.null(inFile)){return(NULL)}
        df <- read.csv(filepath, header = T),
        )
        return(df)
      })
      
       getColumn <- reactive({
        return(as.character(input$getColumn))
      })
      
       updateVarSelectInput(
         inputId = "getColumn",
         data = df(),
         selected = ""
       )
       
       ## my problem is here:
       updateSelectInput(
         inputId = "levels",
         choices = levels(as.factor(df[, getColumn()])),
         selected = NULL
       )
      
      })
    }
  )
)

CodePudding user response:

You have many syntax issues here. In the future, please ensure that you have matching brackets and it is a MRE. The following should work.

library(shiny)

ui = fluidPage(
      fileInput(inputId = "rawFile", label="File"), # Read the dataframe
      varSelectInput(inputId = "getColumn", label="Get Column", data = ""),
      selectInput(inputId = "levels", label="Levels", choices = "")
    )
server = function(input, output, session){
      
  df <- reactive({
    inFile <- input$rawFile
    if (is.null(inFile)){return(NULL)}
    read.csv(inFile$datapath, header = T)
  })
  
  observeEvent(df(),{
    updateVarSelectInput(session, inputId = "getColumn",data = df(),selected = "")
  })
  
  observeEvent(input$getColumn, {
    updateSelectInput(session,inputId = "levels", choices = levels(as.factor(df()[[input$getColumn]])),selected = NULL)
  })
}

shinyApp(ui, server)
  • Related