Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display values in a "numericInput" in shiny as percentage?

Tags:

r

shiny

I have created a shiny web-page and in the sidebarPanel I use several numericInput-fields. Some of them should display values as percentage and it should not be a slider. Does someone have an idea how to format the numericInput-fields?

like image 543
Christian Avatar asked Oct 18 '18 09:10

Christian


1 Answers

I can think of two ways of doing that.

1. Formatted Content

Use a text field in the and parse the content in the server code. The solution can only handle integers at this point. Basically, it works. However, interacting with it does not always give you the best usability.

ui <- fluidPage(
    titlePanel("Parsed Input with Unit Example"),
    textInput("inpPercent", "Chances of Success", value = "20 %"),
    h1(textOutput("txtSuccess"))
)
server <- function(session, input, output) {
  observeEvent( input$inpPercent,{
    Format <- "^[-+]?[ ]*[0-9]*[ ]*[%]?$"

    # Trim
    inp <- gsub("^\\s+|\\s+$", "", input$inpPercent)
    
    if (!grepl(Format, inp)) {
      Result <- "Invalid format"
      inp <- numeric()
    } else {
      # Remove all spaces
      inp <- gsub("[[:space:]]", "", inp)
      # Split
      if (grepl("%", inp)) inp <- gsub("%", "", inp)
      inp <- suppressWarnings( as.numeric(inp) )
      if (is.na(inp)) {
        Result <- "Invalid format2"
        inp <- numeric()
      } else {
        Result <- paste("Percent:", inp)
      }
    }
  
    print(Result)
    output$txtSuccess <- renderPrint(Result)
    if (length(inp) > 0)
      updateTextInput(session, inputId = "inpPercent", value = paste(inp, "%"))
  })
}

2. Shiny Widgets: numericInputIcon

Use the widget numericInputIcon from the shinyWigdets package. It is very easy to set up a widget like that. The documentation provides an example for percentages, too.

Example of a numericInputIcon widget

like image 75
Jan Avatar answered Nov 09 '22 14:11

Jan