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)
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.