0
votes

I have key-value pair data that I want to using in a Shiny selectInput drop down list.

I want the user to select from a list of player names, but I then want to use the corresponding playerID to filter other data sets.

Is there a way to do this? My current code looks like:

selectInput("player","Select a player", Players$fullName),

I want the player drop down to be reactive based on a 'team' drop down. My full code is:

library(shiny)
library(dplyr)

setwd("C:/Users/Michael/Documents/Baseball/Retrosheet/Shiny")
Teams <- read.csv("TeamID.csv")  # List of team names
Players <- read.csv("TeamBatter.csv") # TeamName, fullName, retroID
PlayerData <- read.csv("playerExpectedRBI.csv")  # Data keyed on PlayerID


todrop <- Players$retroID
names(todrop) <- Players$fullName

ui <- fluidPage(

  selectInput("team","Select a team:",Teams$teamID),
  selectInput("player", "Select a player", todrop),
  tableOutput("playerSummary")
)

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

 observe({
      PlayerList <- reactive({Players %>% filter(teamID == input$team) %>%  select(fullName,retroID)})
      updateSelectInput(session,"player", choices=PlayerList()$fullName)
      SelectedPlayerSum <- reactive({PlayerData %>% filter(resbatter == input$player)}) 
      output$playerSummary <- renderTable({SelectedPlayerSum()})
      })

    }

    shinyApp(ui = ui, server = server)

I'm getting the error: Error in (function (choice, name) : All sub-lists in "choices" must be named.

1

1 Answers

0
votes

You basically need to create named list and pass it to dropdown. It will return playerID instead of player fullname.

library(shiny)

Players <- data.frame(fullname = c('John Doe', 'James Smith', 'John Smith'), playerID = c(1:3))
# create named list and pass it to dropdown
todrop <- Players$playerID
names(todrop) <- Players$fullname

ui <- fluidPage(
    selectInput("player","Select a player", todrop),
    uiOutput("out")
)

server <- function(input, output) {

    output$out <- renderUI({
        print(paste0("Players ID is: ", input$player)) # here you select player ID from dropdown (not fullnames) and can use input$player for your queries
    })
}

shinyApp(ui = ui, server = server)