0

I am creating an R Shiny app where I have an extremely long list of options for selectInput. Depending on the option you select, the value is going to change. I know that for a small list of options you can set the values yourself in the server function like so:

server <- function(input, output) {
  output$graph <- renderPlot({
    player <- switch(input$var, 
                   "LeBron James" = 23,
                   "Kobe Bryant" = 24,
                   "DeMar DeRozan" = 10,
                   "Kyle Lowry" = 7)
    plotGraph(player)

  })
}

But my list has at least 100 options and it's certainly not clean nor efficient to set the values like this for all 100 options. Is there a way to set the values depending on the option selected without having to do it manually?

Below is my code in my ui function

ui <- fluidPage(
    titlePanel(h1("Fantasy Dashboard")),
    
    sidebarLayout(
        sidebarPanel(h2("Player Name Goes Here"),
            selectInput("playername", 
                        label = "Choose a player",
                        choices = player_choices,
                        selected = NULL),
        ),
        

        mainPanel(plotOutput("graph"))
        
    )
)

The choices will be stored in player_choices. These choices are read from a txt file. And depending on the option selected, the variable player should be set to the corresponding value. Thanks in advance!

Waldi
  • 39,242
  • 6
  • 30
  • 78

1 Answers1

0

Try:

library(shiny)

playernames <- list("Smith","Johnston","Andrew")

shinyApp(
  ui = fluidPage(
    uiOutput("selectname"),
    textOutput("result")
  ),
  server = function(input, output) {
    output$selectname <- renderUI( {
      selectInput("playername", "Choose player",playernames)})
    output$result <- renderText({
      paste("You chose", input$playername)
    })
  }
)

The playernames list can also be reactive and be modified by other inputs.

Waldi
  • 39,242
  • 6
  • 30
  • 78