Sam Sam - 3 months ago 24
R Question

Keeping Shiny Reactive Radio Buttons Constant

I am attempting to create some reactive radio buttons in Shiny, and am running into some issues. The code below creates an example of what I am seeing. For example, there are three selections for numbers - 1, 2, and 3. Each of these have their own possible letter selections - if 1 or 3 are selected, A or B are available, but if 2 is selected, A, B, or C are available.

The problem lies in that I would like the second set of radio buttons to only display options available depending on the number selection. However, the letter selection resets every time I select a new number. So if I have 2 and B selected, and then change the number to 1, it automatically changes the letter selection to A. I would like the second selection to stay, if it is an option, such that if I selected 2 and B, I could then change the number to whatever I like, and B would stay selected. But if I had selected 2 and C, then changed the number to 1, obviously there is no C under 1, so then it would have to reset to some default (A, most likely).

How would I go about setting up the radio buttons to behave in this manner?

library('shiny')
library('shinydashboard')

# Input Data
inputData <- data.frame(a = c(1, 1, 2, 2, 2, 3, 3),
b = c('A', 'B', 'A', 'B', 'C', 'A', 'B')
)

# Body #############################
body <- dashboardBody(

radioButtons('selectA', 'Select Number',
choices = unique(inputData$a)),

uiOutput('selectB')
)

# UI #############################
ui <- dashboardPage(
dashboardHeader(title = 'Test', titleWidth = 290),
dashboardSidebar(width = 290),
body
)

# Server #############################
server <- function(input, output){

output$selectB <- renderUI({
radioButtons('selectB', 'Select Letter',
choices = unique(inputData[inputData$a == input$selectA, ]$b),
inline = TRUE)
})
}

shinyApp(ui, server)

Answer

You can test whether something is selected on the first set of radioButtons and choose the selected argument of the second set of radioButtons accordingly, like this:

output$selectB <- renderUI({
    if(is.null(input$selectB)){
      radioButtons('selectB', 'Select Letter', 
                 choices = unique(inputData[inputData$a == input$selectA, ]$b),
                 inline = TRUE)
    }
    else{
      radioButtons('selectB', 'Select Letter', 
                   choices = unique(inputData[inputData$a == input$selectA, ]$b),
                   inline = TRUE, selected = input$selectB)
    }
  })
Comments