【问题标题】:Use string as name to create new output element使用字符串作为名称来创建新的输出元素
【发布时间】:2016-08-09 10:29:34
【问题描述】:

我正在寻找一种方法来即时为output 赋值。 这个想法是每次点击一个动作按钮,一个新的渲染对象(例如text_1text_2,...)被保存在output中。为了实现这一点,我已经有了一个在使用按钮时增加一的变量。现在,我想使用一些常量字符串以及这个变量来为输出对象创建一个名称(类似于paste0("output$text_",i)。我遇到的问题是我只知道如何用@向output添加一些东西987654328@。但是这种方式我不能使用字符串作为变量名(至少我是这么认为的)。使用assign 它也不起作用。还有其他方法可以做我想要的吗?

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)

【问题讨论】:

标签: r shiny


【解决方案1】:

此解决方案基于https://gist.github.com/wch/5436415/。希望对你有帮助:)

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2012-04-23
    • 2019-04-25
    • 1970-01-01
    • 2012-12-26
    • 2012-06-10
    • 2015-02-21
    • 2013-04-12
    相关资源
    最近更新 更多