【问题标题】:Avoid sliderInput rounding避免滑块输入舍入
【发布时间】:2020-01-26 23:27:37
【问题描述】:

当最小/最大范围较大时,sliderInput 舍入我的起始值参数时遇到问题。在以下示例的情况下,如何防止 sliderInput 舍入我的起始值参数?

library(shiny)

ui <- fluidPage(
    sliderInput(
      inputId = "test",
      label = "A Nice Label",
      min = 2.52,
      max = 45734.68,
      value = 30982.63, # auto rounded to nearest integer in application, which I do not want it to do.
      round = FALSE # tried this argument, no dice.
    ),
    verbatimTextOutput(
      "value"
    )
  )

## SERVER PROCESSING DEFINITION
# this section defines how data is processed in response to manipulations in the ui
server <- function(input, output, session) {

  output$value <- renderText({
    input$test
  }) 

}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您需要提供step = 参数以任意提高精度。文档说默认情况下“使用启发式”来确定步长,这会导致您观察到的舍入。查看此更新版本:

    library(shiny)
    
    ui <- fluidPage(
      fluidPage(
        sliderInput(
          inputId = "test",
          label = "A Nice Label",
          min = 2.52,
          max = 45734.68,
          step = 0.01,      # the smallest level of precision in your args
          value = 30982.63, # no longer rounded
          round = FALSE     # this is the default
        ),
        verbatimTextOutput(
          "value"
        )
      )
    )
    
    ## SERVER PROCESSING DEFINITION
    # this section defines how data is processed in response to manipulations in the ui
    server <- function(input, output, session) {
    
      output$value <- renderText({
        sprintf("%5.6f", input$test)       # format text to show precision
      }) 
    
    }
    
    shinyApp(ui, server)
    

    如果您深入研究sliderInput,您会发现shiny:::findStepSize 的以下定义:

    function (min, max, step) 
    {
      if (!is.null(step)) 
        return(step)
      range <- max - min
      if (range < 2 || hasDecimals(min) || hasDecimals(max)) {
        pretty_steps <- pretty(c(min, max), n = 100)
        n_steps <- length(pretty_steps) - 1
        signif(digits = 10, (max(pretty_steps) - min(pretty_steps))/n_steps)
      }
      else {
        1
      }
    }
    

    所以你可以看到它试图在你的最小值和最大值之间有大约 100 步,所以它们会自动四舍五入为整数(甚至更大的步长)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多