Search code examples
rshinyordinal

How to get the order of an ordinal variable from users on R Shiny


I'd like to get a string of numbers from users, such as 3,2,1 or 3,1,2 and use this information to order an ordinal variable. Here is my code but it's not working.

server.R:

function(input, output, session) {
    eventReactive(input$run_ord, {
        order=c(input$correct_order)
    })

    output$ntext <- renderText({
      print(str(order()))
  })
}

ui.R:

fluidPage(theme = shinytheme("spacelab"),
    navbarPage(("Structure"), id = "allResults",

        tabPanel(value='set_ord', title = 'Ordinality',
                 sidebarLayout(
                   sidebarPanel(
                       h5("Specify the correct order below"),
                       #price_tiers_new : Mainstream ; Premium ; Super Premium ; Value ;
                       textInput("correct_order", "","4,1,2,3"),

                       actionButton("run_ord", "Run!"),
                       width = 3
                   ),

                   mainPanel(
                     verbatimTextOutput("ntext")
                   )
    )
)
)
)

The idea is : if users enter 3,1,2, I would use this in order=c(3,1,2) in a function that does the reordering.

Any input is appreciated. Thank you!


Solution

  • @Micael Bird alreay said it all. You need to convert the string into a numeric vector somehow. Here is a solution using strsplit function from the stringi package.

    Two quick notes

    • order should be the return value of èventReactive.
    • Use renderPrint rather than renderText if you want to display outputs that can not be coerced to a string.

    Server code:

    library(dplyr)
    library(stringi)
    
    function(input, output, session) {
      order = eventReactive(input$run_ord, {
        strsplit(input$correct_order,",") %>% unlist %>% as.numeric()
      })
    
      output$ntext <- renderPrint({
        str(order())
      })
    }