是否可以创建一个以递减顺序显示值的sliderInput(从左到右;例如5 4 3 2 1)?

runApp(
 list(
  ui = fluidPage(
   sliderInput("test","", min=5, max=1, value = 3, step=1)
   ),
   server = function(input,output) {}
  )
 )

最佳答案

编辑2017-10-13:此功能现在在软件包shinyWidgets中可用(具有不同的名称:sliderTextInput())。

嗨,您可以像这样编写自己的滑块函数(有点脏...):

sliderValues <- function (inputId, label, values, from, to = NULL, width = NULL) {
        sliderProps <- shiny:::dropNulls(list(class = "js-range-slider",
                                      id = inputId,
                                      `data-type` = if (!is.null(to)) "double",
                                      `data-from` = which(values == from) - 1,
                                      `data-to` = if (!is.null(to)) which(values == to) - 1,
                                      `data-grid` = TRUE,
                                      `data-values` = paste(values, collapse = ", ")
                                      ))
        sliderProps <- lapply(sliderProps, function(x) {
          if (identical(x, TRUE))
            "true"
          else if (identical(x, FALSE))
            "false"
          else x
        })
        sliderTag <- div(class = "form-group shiny-input-container",
                         style = if (!is.null(width))
                           paste0("width: ", validateCssUnit(width), ";"),
                         if (!is.null(label))
                           shiny:::controlLabel(inputId, label), do.call(tags$input,
                                                                 sliderProps))
        dep <- list(htmltools::htmlDependency("ionrangeslider", "2.0.12", c(href = "shared/ionrangeslider"),
                                   script = "js/ion.rangeSlider.min.js",
                                   stylesheet = c("css/ion.rangeSlider.css",
                                                  "css/ion.rangeSlider.skinShiny.css")))
        htmltools::attachDependencies(sliderTag, dep)
      }


这样做的目的是使用ionrangeslider的values属性(请参阅使用自定义值数组here部分)。

缺点是您在服务器端检索的输入值不是滑块的值,而是值的索引(从0开始)。

您可以像这样使用此功能:

library("shiny")
runApp(
  list(
    ui = fluidPage(
      # you have to pass the values you want in the slider directly to th function
      sliderValues(inputId = "test", label = "", from = 5, values = 5:1),
      verbatimTextOutput(outputId = "slidervalue")
    ),
    server = function(input,output) {
      output$slidervalue <- renderPrint({
        # Careful ! : input$test isn't the expected value !!!
        (5:1)[input$test + 1]
      })
    }
  )
)


和加分:它也适用于字符向量:

runApp(
  list(
    ui = fluidPage(
      sliderValues(inputId = "test", label = "", from = "g", to = "o", values = letters),
      verbatimTextOutput(outputId = "slidervalue")
    ),
    server = function(input,output) {
      output$slidervalue <- renderPrint({
        # Careful ! : input$test isn't the expected value !!!
        letters[input$test + 1]
      })
    }
  )
)

10-04 21:05