如何访问和更改 R Shiny server.r 中的输入变量

Mik*_* C. 0 r shiny

对不起,如果这是一个常见问题,但它让我发疯。我需要将 actionButton 添加到触发文件保存的 Shiny UI。实际的文件保存命令取决于 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
        )
    )
))
Run Code Online (Sandbox Code Playgroud)

在 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
    }
})
Run Code Online (Sandbox Code Playgroud)

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

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

最好的,--Mike C.

Joe*_*eng 5

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

observe({
  if (input$save == 0)
    return()

  isolate({
    # Do your saving in here
  })
})
Run Code Online (Sandbox Code Playgroud)

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