My goal is to have the user select from a list of unique team names from my dataframe, and then store that input value to be used later on. It seems like a really easy problem, but my problem is when I try to access the input value using input$team_choice_1, I get an error message stating "Can't access the reactive value 'team_choice_1' outside of the reactive consumer.", and then it prompts me to use reactive() or observe(). I've being trying to use reactive(), but I still can't access the value from the input.
Welcome to the community @sro! Below is an example app that illustrates a couple different ways to access data selected by a user. In the first case, input$team_choice_1 is called directly within a renderText() function. In the second case, the input is first captured in a reactive(), and then that reactive (mydata) is called within a renderText() function to generate a sentence. The final line (test = ...), which is commented out, attempts to call input$team_choice_1 without wrapping it in a render() or reactive() first. If you uncomment this line and run the app, you will encounter the error you described.
I hope this helps illustrate how to properly call an input from within an app.
library(shiny)
df = data.frame(TEAM.x = c('Team A', 'Team B', 'Team C'))
all_teams <- sort(unique(df$TEAM.x))
ui <- fluidPage(
br(),
selectInput("team_choice_1",
label = "Choose Team 1",
choices = all_teams,
selected = all_teams[1],
multiple = F),
br(),
textOutput('team_text'),
br(),
textOutput('team_sentence')
)
server <- function(input, output, session) {
# output the selection directly
output$team_text = renderText(input$team_choice_1)
# capture the selection in a reactive
mydata = reactive(input$team_choice_1)
# output the selection via the reactive
output$team_sentence = renderText({
req(mydata)
paste0('The team I selected is ', mydata())
})
# test = input$team_choice_1 # something like this would cause an error
}
shinyApp(ui, server)
Thank you Scotty! That fixed the problem that I asked about originally, but now I'm running into another problem: I have another selectInput that is dependent on the first input, now giving the option to choose players from the team selected in the first input. In my mind, the code for the second select Input would look like:
But, I know that this will run into an error since the selectInput function is not wrapped within a reactive() function. When I do wrap it in the reactive() function, however, the input selection doesn't populate in the dashboard, instead it just displays the HTML for the selectInput function. Do you have any suggestions on how I can fix this?
Another approach I was thinking of was somehow finding a way to parse the reactive input into a usable string, but I have yet to find a way to do that.