1

如何将其他参数传递给 Shiny 中的反应式上下文?目的是在评估时将参数移交给反应式上下文(“回调”)。

想想下面的 Shiny 服务器代码。我怎样才能output$some打印“一些”,output$different打印“不同”等等?

for(i in c("some","different","values"){
  output[[i]] <- renderText({
  # i gets evaluated at some later point in time, 
  # and thus will always print "values"
  i
})
}

下面的示例旨在使两个渲染上下文对相应的响应值text1和具有反应性text2,但当然它只使两者都依赖于text2

library(shiny)
ui <- fluidPage(
   titlePanel("Test"),
   sidebarLayout(
      sidebarPanel(
      ),
      mainPanel(
        htmlOutput("text1"),
        textOutput("text2"),

        actionButton("test_btn1",label="test1"),
        actionButton("test_btn2",label="test2")
      )
   )
)
server <- function(input, output) {
  rv <- reactiveValues(
    "text1"=NULL,
    "text2"=NULL
  )
  bindings <- list(
    list("var"="text1",
         "function"=renderUI),
    list("var"="text2",
         "function"=renderText)
  )
  for(i in bindings){
    output[[i[["var"]]]] <- i[["function"]]({
      # i is always the second element unfortunately
      rv[[i[["var"]]]]
    })
  }
  observeEvent(input$test_btn1,{
    rv$text1 <- tags$p("new value 1")
  })
  observeEvent(input$test_btn2,{
    rv$text2 <- "new value 2"
  })
}
shinyApp(ui = ui, server = server)
4

1 回答 1

1

尝试使用 Map() 而不是 for 循环,以便在每次迭代中调用该函数:

library(shiny)
ui <- fluidPage(
  titlePanel("Test"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      htmlOutput("text1"),
      textOutput("text2"),

      actionButton("test_btn1",label="test1"),
      actionButton("test_btn2",label="test2")
    )
  )
)
server <- function(input, output) {
  rv <- reactiveValues(
   "text1"=NULL,
    "text2"=NULL
  )
  bindings <- list(
    list("var"="text1",
         "function"=renderUI),
    list("var"="text2",
         "function"=renderText)
  )

  Map(function(i){
    output[[bindings[[i]][["var"]]]] <- bindings[[i]][["function"]]({
      # i is always the second element unfortunately
      rv[[bindings[[i]][["var"]]]]

    })
  }, 1:2)
  observeEvent(input$test_btn1,{
    rv$text1 <- "new value 1"
  })
  observeEvent(input$test_btn2,{
    rv$text2 <- "new value 2"
  })
}
shinyApp(ui = ui, server = server)
于 2018-06-08T15:16:46.517 回答