neringab
neringab

Reputation: 645

Shiny selectinput filtering

I have shiny code:

# ui.R
fluidPage(
  selectInput("ci_risk_1000M", "<=", 
              choices = c("a" = 1, "b" = 2, "c" = 3, "d" = 4, "e" = 5, "f" = 6, 
                          "g" = 7, "h" = 8, "i" = 9, "j" = 10, "k" = 11), 
              selected = 11), 
  tableOutput("ats")

)
# server.R
x <- 1:11
    function(input, output, session) {
     output$ats <- renderTable({x[x <= input$ci_risk_1000M]}) 
    }

I want to filter x values by selected input. However, the basic answer should be table with rows from 1 to 11, but it shows me only values 1, 10, 11. Do you know why and how i can fix that? sliderInput is not the option, unless it could be shown as character values, not integers.

Upvotes: 1

Views: 320

Answers (1)

akrun
akrun

Reputation: 887961

The problem is in the output of input$ci_risk_1000M which is character class.

If we check how it behaves on a character vector

x <= "11"
#[1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE

i.e. only the first, tenth and eleventh are TRUE, so the subset returns

x[x <= "11"]
#[1]  1 10 11

Also, checking how the character vector behaves with sorting

sort(as.character(x))
#[1] "1"  "10" "11" "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9" 

We need to convert it to numeric/integer

output$ats <- renderTable({x[x <= as.integer(input$ci_risk_1000M)]}) 

-full code

library(shiny)
ui <- fluidPage(
  selectInput("ci_risk_1000M", "<=", 
              choices = c("a" = 1, "b" = 2, "c" = 3, "d" = 4, "e" = 5, "f" = 6, 
                          "g" = 7, "h" = 8, "i" = 9, "j" = 10, "k" = 11), 
              selected = 11), 
  tableOutput("ats")

)
# server.R
x <- 1:11
server <- function(input, output, session) {
  output$ats <- renderTable({x[x <= as.integer(input$ci_risk_1000M)]}) 
}
shinyApp(ui, server)

-output

enter image description here

Upvotes: 1

Related Questions