传递参数以在Shiny中渲染函数

时间:2018-06-08 11:58:49

标签: r function scope shiny shiny-reactivity

如何将其他参数传递给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
})
}

下面的示例旨在使两个渲染上下文对相应的反应值text1text2起反应,但当然它只使两者都依赖于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)

1 个答案:

答案 0 :(得分: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)