【问题标题】:How to display values in a "numericInput" in shiny as percentage?如何以闪亮的百分比显示“numericInput”中的值?
【发布时间】:2021-12-03 05:11:49
【问题描述】:

我创建了一个闪亮的网页,并在侧边栏面板中使用了几个数字输入字段。其中一些应该以百分比显示值,而不应该是滑块。 有人知道如何格式化数字输入字段吗?

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我可以想到两种方法。

    1。格式化内容

    在服务器代码中使用文本字段并解析内容。该解决方案此时只能处理整数。基本上,它有效。然而,与之交互并不总是为您提供最佳可用性。

    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。闪亮的小部件: numericInputIcon

    使用shinyWigdets 包中的小部件numericInputIcon。设置这样的小部件非常容易。该文档也提供了百分比示例。

    【讨论】:

    • 只是指出它应该是带有大写 W 的 shinyWidgets,但如果我打开您指向 shinyWidgets 的链接,就会很明显。
    【解决方案2】:

    您可以像这样使用带有 format = "percentageUS2dec" 的 shinyWidgets::currencyinput

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

    导致以下输入

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 2021-03-04
      • 1970-01-01
      • 2016-04-26
      • 2017-06-02
      • 2020-05-20
      • 1970-01-01
      • 2017-11-21
      • 2020-12-15
      相关资源
      最近更新 更多