How to use Shiny inputs in a string for reactive function and as a condition for observe event

Viewed 251

I am trying to use auto generated selectInput IDs inside the reactive element or observe event. When I explicitly write the input IDs like input$dfSelect1,input$dfSelect2,input$dfSelect3, it works as I wanted.

Since I don't know in advance how many IDs will be there (data will be user input), I need to create same input ID strings as automated, but it doesn't recognize it as a trigger in observe event or a input data in reactive element.

Here is the minimal reproducible example of my problem. if you comment out the line 1 req(input$dfSelect1,input$dfSelect2,input$dfSelect3) and line 2 dfx <- data.frame(carb = c(input$dfSelect1,input$dfSelect2,input$dfSelect3),stringsAsFactors = F) and remove the comment from the following lines, this will be the case I am trying to do.

any idea how to pass these values?

library(dplyr)
library(DT)

exdata <- head(mtcars, 3) 
exdata$ROWs <- row.names(exdata)

ui <- fluidPage(
  headerPanel("Example"),
  mainPanel(
    uiOutput("selectionUI"),
    uiOutput("tableOutput")
  )
)

server <- function(input, output, server) {

  ### reqString result <- input$dfSelect1,input$dfSelect2,input$dfSelect3
  reqString <- noquote(paste0(unlist(lapply(1:length(sort(unique(row.names(exdata)))),function(i) {paste0("input$dfSelect",i,"")})),collapse = ","))

  values <- reactiveValues(
    upload_state = NULL
  )

  observe({
    ### 1-USE the line below with reqString instead -doesn't work ##
    req(input$dfSelect1,input$dfSelect2,input$dfSelect3)
    # req(reqString)
    values$upload_state <- 'uploaded'
  })

  output$selectionUI <- renderUI({
    df <- sort(unique(row.names(exdata)))
    wellPanel(
      lapply(1:length(df), function(i) {selectizeInput(paste0("dfSelect",i,""),df[i],choices=c("", unique(exdata$carb)))})
    )
  })

  completeTable <- reactive({
    browser()
    if (is.null(values$upload_state)) {
      return(exdata)
    }else if (values$upload_state == 'uploaded') {
      ### 2-USE the line below with  reqString instead -doesn't work##
      dfx <- data.frame(carb = c(input$dfSelect1,input$dfSelect2,input$dfSelect3),stringsAsFactors = F)
      # dfx <- data.frame(carb = c(reqString),stringsAsFactors = F)
      dfx <- data.frame(carb =as.numeric(unlist(dfx)))
      dataJoin <- exdata %>% left_join(dfx,by=("carb"))
    }
  })

  output$tableOutput <- renderUI({
    DT::dataTableOutput("dataTableServer")
  })

  output$dataTableServer <- DT::renderDataTable({
    DT::datatable(completeTable())
  })

}

shinyApp(ui = ui, server = server)
1 Answers

You can index input using [[ instead of $:

sapply(1:length(sort(unique(row.names(exdata)))), 
       FUN=function(x) req(input[[paste0("dfSelect", x)]]))

and

l <- sapply(1:length(sort(unique(row.names(exdata)))), 
            FUN=function(x) input[[paste0("dfSelect", x)]])
dfx <- data.frame(carb = l,stringsAsFactors = F)
Related