skad00sh
skad00sh

Reputation: 171

Access dynamic id in shiny R

So this is an extension to my previous question.

Dynamic repeating conditionalPanel in R shiny dashboard

Here is the shiny code I am using right now.

library(shiny)
library(shinydashboard)

ui <- fluidPage(
  br(),
  selectInput("inpt", "Input Number", seq(1,50), selectize = FALSE),
  br(),
  uiOutput("selectors")
)

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

  output[["selectors"]] <- renderUI({
    n <- input[["inpt"]]
    selectors <- lapply(1:n, function(i){
      selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
    })
    do.call(function(...){
      box(..., width = 2, status = "primary")
    }, selectors)
  })

}

shinyApp(ui, server)

It will generate selection windows depending on 'inpt' number selection.

Now my issue is that I want to access the value of generated selection input.

Example: If I have selected 3, three inputs will be generated with id1, id2, id3.

How to access these ids? If I want to print them, how can I?

for (j in 1:inpt){ 
    print(eval(parse(text = paste0("input$", paste0("id",j)))))
}

But output for this is:

NULL
NULL
NULL

I thought my eval and parse method is wrong so I tried with just inpt

for (j in 1:inpt){ 
    print(eval(parse(text = paste0("input$", paste0("in","pt")))))
}

Output was (3 was selected in selection input)

3
3
3

So my eval, parse method was correct I guess. So how to access id1, id2, ..., idn in above example?

Upvotes: 1

Views: 1042

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33510

Please check the following:

library(shiny)
library(shinydashboard)

ui <- fluidPage(
  br(),
  selectInput("inpt", "Input Number", seq(1,50), selectize = FALSE),
  br(),
  uiOutput("selectors"),
  uiOutput("printMyDynamicInputs"),
  uiOutput("printMyFirstDynamicInput")
)

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

  output[["selectors"]] <- renderUI({
    n <- input[["inpt"]]
    selectors <- lapply(1:n, function(i){
      selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
    })
    do.call(function(...){
      box(..., width = 2, status = "primary")
    }, selectors)
  })

  myDynamicInputs <- reactive({
    lapply(1:input$inpt, function(i){
      input[[paste0("id",i)]]
    })
  })

  output$printMyDynamicInput <- renderUI({
    paste("You selected:", paste(myDynamicInputs(), collapse = ", "))
  })

  output$printMyFirstDynamicInputs <- renderUI({
    paste("You selected:", input$id1)
  })

}

shinyApp(ui, server)

Result

Upvotes: 2

Related Questions