简体   繁体   中英

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

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?

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.

numericInputIcon 小部件的示例

You can use shinyWidgets::currencyinput with format = "percentageUS2dec" like this

currencyInput("perc", "Example", value = 0.3, format = "percentageUS2dec"),

Resulting in the following input在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM