【问题标题】:How to access and change an input variable in R Shiny server.r如何在 R Shiny server.r 中访问和更改输入变量
【发布时间】:2014-07-12 01:58:48
【问题描述】:

对不起,如果这是一个常见问题,但这让我发疯了。我需要向触发文件保存的 Shiny UI 添加一个 actionButton。实际的文件保存命令取决于 tabPanel 的哪个选项卡打开,我可以通过 tabPanel id 获取该信息。我遇到的问题是访问 actionButton 的状态并在之后重置它。

在 ui.r 中,我有这样的东西:

shinyUI(fluidPage(
    titlePanel("myTitle"),

    sidebarLayout(
        sidebarPanel("",
            actionButton("save", "Save File"),

            # test to make sure the button is working
            verbatimTextOutput("sb")    # it increments when clicked
        )
    )
))

在 server.r 中,我正在尝试这样做:

shinyServer(function(input, output) {

    # test to make sure the button is working
    output$sb <- renderPrint({ input$save })     # increments when clicked

    # here is the problem code:
    if(input$save > 0) {                         # button was clicked, so...
        input$save <- 0                          # reset the flag
        print("HERE")                            # and do something else
    }
})

当然,我会检查 tabPanel 的状态,而不是打印“HERE”,如果我解决了这个问题,这可能会产生另一个问题。如何访问和更改 server.r 代码中 input$save 的值?没有证据表明 if() 条件语句中的代码正在执行,所以我假设逻辑测试要么没有被执行,要么返回 FALSE,即使每次单击按钮时 input$save 的值都会增加。

感谢您的任何建议。可能很明显,我对 Shiny 很陌生,到目前为止发现它相当不透明。

最好, ——迈克 C.

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    如果您的代码需要在输入更改时重新执行,它不能像您现在拥有的if 那样位于您的服务器函数中。你需要把它放在一个观察块中:

    observe({
      if (input$save == 0)
        return()
    
      isolate({
        # Do your saving in here
      })
    })
    

    您绝对不需要将 input$save 的值重置为 0。我全心全意地相信,我特意将该功能排除在框架之外。 input$save 的实际值是没有意义的,除了值 0 表示“按钮从未被点击过”;对于其他每个值,值本身并不重要,只是它发生了变化。每次到达# Do your saving in here 行时,这意味着用户单击了“保存”按钮。无论是第 1 次还是第 100 次被点击都无关紧要;事实上,用户刚刚点击了它,您现在应该保存。

    【讨论】:

      【解决方案2】:

      我猜代码只会在您启动shinyServer 时运行一次。我认为您需要在 reactive 块内才能运行模型更改。否则,现在的代码块将永远不会被重新评估。

      【讨论】:

        猜你喜欢
        • 2021-04-14
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 2014-04-20
        • 2017-03-06
        相关资源
        最近更新 更多