Search code examples
rshinyshinywidgets

sliderTextInput displays incorrect values?


I'm trying to output a certain number based on the value from sliderTextInput, but for some reason, it doesn't seem to be displaying the right value as the slider changes. My list of choices for the sliderTextInput are ("0", "1", "2", ">2"), and for each of these values, it's supposed to render a text value of (0, 25, 50, 75), but the value for 0 is usually never displayed, and the values seem to be shifted by one value. Here is a reproducible example of the issue:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  sliderTextInput("slider1", label = "What is your Score?", 
                  choices = c("0","1", "2", ">2"), selected = "0"),

    textOutput("score")
)

server <- function(input, output, session) {
  output$score <- renderText(switch(input$slider1,
                                  "0"  = 0,
                                  "1"  = 25,
                                  "2"  = 50,
                                  ">2" = 75))
}
shinyApp(ui, server)

I thought it might be because it can't interpret a mix of strings and numbers (e.g. ">2" vs "2"), or the value 0 might be interpreted differently, but changing these had no effect. The only way I was able to get it to work is if I changed every input value to a clear string (e.g. "Zero", "One", "Two", ">Two"). However, doesn't enclosing the numbers with quotes force evaluation as character, and not as a number? Or is the error something I am missing entirely?


Solution

  • switch requires exact match, but if you output:

    output$score <- renderText(class(input$slider1))
    

    you'll see that the 3 first choices return integer whereas the last one returns character.

    Casting input$slider1 to character works:

    library(shiny)
    library(shinyWidgets)
    
    ui <- fluidPage(
      sliderTextInput("slider1", label = "What is your Score?", 
                      choices = c("0","1", "2", ">2"), selected = "0"),
      
      textOutput("score")
    )
    
    server <- function(input, output, session) {
      output$score <- renderText(switch(as.character(input$slider1),
                                        "0"  = 0,
                                        "1"  = 25,
                                        "2"  = 50,
                                        ">2" = 75))
    }
    shinyApp(ui, server)