1

I am looking for a way to assign values to output on the fly. The idea is that each time an action button is hit, a new render object (e.g. text_1, text_2, ...) is saved in output. To achieve this I already have a variable which increases by one when the button is used. Now, I would like to use some constant string in addition with this variable to create a name for an output object (something like this paste0("output$text_",i). The problem I have is that I only know how to add something to output with <-. But this way I can't use a string as variable name (at least I think so). With assign it did not work as well. Is there another way to do what I want?

library(shiny)
ui <- fluidPage(

  textOutput("text_1")
  textOutput("text_2")

)

server <- function(input, output) {

  output$text_1<- renderText({ "Hi" })                          #standard
  assign(paste0("output$text_",2), renderText({ "Hello" }) )    #sth. I would like to do

}

shinyApp(ui = ui, server = server)
Alex
  • 4,925
  • 2
  • 32
  • 48

1 Answers1

1

This solution is based on https://gist.github.com/wch/5436415/. I hope it helps :)

library(shiny)


ui <- shinyUI(fluidPage(

   titlePanel(""),

   sidebarLayout(
      sidebarPanel(
         sliderInput("number", "Some numbers", min = 1, max = 10, value = 1)
      ),

      mainPanel(
        uiOutput("dynamic")
      )
   )
))

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

  output$dynamic <- renderUI({
    text_output_list <- lapply(1:input$number, function(i) {
      textname <- paste("text_", i, sep = "")
      textOutput(textname)
    })
    do.call(tagList, text_output_list)
  })

  for (i in 1:1000) {

    local({
      my_i <- i
      textname <- paste("text_", my_i, sep = "")
      output[[textname]] <-  renderText({ paste("Hi", my_i) })
    })
  }
})

# Run the application 
shinyApp(ui = ui, server = server)
Michal Majka
  • 5,332
  • 2
  • 29
  • 40