在 Shiny 中创建可变数量的 `sliderInput`

Create a variable number of `sliderInput` in Shiny

我的数据是一个列数可变的矩阵。此外,矩阵中值的范围也是可变的。 我想构建一个可变数量的 sliderInput,每个对应于矩阵中的一列。 每个滑块的上限应对应矩阵内的maxRange。 有什么建议可以一次性完成吗?

 lapply(1:ncol, function(i) {
        sliderInput(
          paste0('a', i), 
          paste0('SelectA', i),
          min = min(c(1:maxRange)),
          max = max(c(1:maxRange)),
          value = c(1, maxRange),
          step =1
          )
      }
      )

当我想创建一组对应于从数据集派生的值(最小、最大选项列表等)的输入元素时,我遇到了大致相似的问题。从广义上讲,我会通过 global.R 获取所有必需的数据,然后引用元素中的概念,因此在滑块中获取 min/max 的行中:

global.R

# Get dates for the slider
## Delete pointless month
dta.nom$DATE_NAME <- sub("February ", replacement = "", x = dta.nom$DATE_NAME)
## Convert to number and get min/max
dta.nom$DATE_NAME <- as.numeric(x = dta.nom$DATE_NAME)
yr.min <- min(dta.nom$DATE_NAME)
yr.max <- max(dta.nom$DATE_NAME)

然后在滑块中

ui.R

# Select the dates for the data
sliderInput("sliderYears", label = h5("Years"), min = yr.min, 
            max = yr.max, value = c(2000, 2010), sep = "",
            step = 1, animate = FALSE), 

完整代码在 GitHub. I'm not sure if I understood you correctly but if you are interested in dynamically connecting elements of your interface in Shiny then you can make use of the updateSelectInput。使用 global 代码并引用界面元素中的值应该可以解决与引用数据有关的任何其他问题。

以防有人遇到同样的问题,这是我的解决方案:

ui.R

    .... 
    sidebarPanel(
        selectInput(
            inputId = "dataName",
            label   = "Select your data",
            choices = c("data1", "data2", "data3", "data4")
          ),

        uiOutput(outputId = "sliders")
    ),
   .....
    

server.R

  .....
  output$sliders <- renderUI({
      numSliders <- numCols(input$dataName)
      lapply(1:numSliders, function(i) {
        sliderInput(
                    inputId = paste0('column', i),
                    label = paste0('Select the range for column ', i),
                    min = min(selectRange(input$dataName)),
                    max = max(selectRange(input$dataName)),
                    value = c(min(selectRange(input$dataName)), max(selectRange(input$dataName))),
                    step =1)
        })
    })
........

selectRangeglobal.R 中的另一个函数:

global.R

selectRange <- function(x){
  if(x == "data1"){choices = c(1:100)}
  if(x == "data2"){choices = c(1:50)}
  if(x == "data3"){choices = c(1:75)}
  if(x == "data4"){choices = c(1:150)}
return(choices)  
}