Search code examples
rshinyshiny-server

How to observe individual input elements which were created in bulk in R Shiny


I have a set of sliderInputs whose number equals the number of columns in my data. The number of columns is determined by the values of choices from global.R. Each slider is associate to one column and were created as shown bellow in server.R and ui.R.

I would like to observe them individually so I can apply the values to the associated column. Something like in this example. Any suggestion?

 #Example. Not valide code!!!
 selectedValBySliders <- observe({ 
    print("Numbers selected via sliders:") 
    out_sliders <- input$sliders[1:numSliders]
    print(out_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)
        })
    })

ui.R

            uiOutput(outputId = "sliders"),

global.R

 selectRange <- function(x){
  if(x == "data1"){choices = c(1:10)}
  if(x == "data2"){choices = c(1:15)}
  if(x == "data3"){choices = c(1:20)}
  if(x == "data4"){choices = c(1:25)}
return(choices)  
}

 numCols <- function(x){
  if(x == "data1"){ncolumns = 4}
  if(x == "data2"){ncolumns = 5}
  if(x == "data3"){ncolumns = 5}
  if(x == "data4"){ncolumns = 6}
return(ncolumns)  
}

Solution

  • In case someone might bump into the same issue, here is my solution. Feel free to update it with a better answer if you have one.

      minMax <- matrix(0, ncol(getData), 2)
      for(i in seq(ncol(getData))){
        if(!is.null(input[[paste0('column', i)]])){
        val <- input[[paste0('column', i)]]
        minMax[i,] <- val
        index <- which(getData[, i] %in% c(minMax[i, 1]:minMax[i, 2]))
        selectedSet <- getData[index, ]
      }
    }