【问题标题】:Passing arguments to render functions in Shiny将参数传递给 Shiny 中的渲染函数
【发布时间】:2018-11-18 11:41:56
【问题描述】:

如何在 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)

【问题讨论】:

    标签: r function scope shiny shiny-reactivity


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多