【问题标题】:How to get a reactive data.frame in a shiny application如何在闪亮的应用程序中获取响应式 data.frame
【发布时间】:2020-12-16 11:07:17
【问题描述】:

我想知道如何让我的闪亮应用对任何对 data.frame 的修改做出反应。这在很多方面都很有用。比如:

[server part]
rv <- reactiveValues(
  df <- data.frame(...)
)

observeEvent(rv$df, {
  ...
})

【问题讨论】:

    标签: r shiny reactive


    【解决方案1】:

    这是我想出的一个解决方案的示例。请注意,这只是一个用例(没有模块)。我会告诉你,我成功地将它应用于更复杂的应用程序(> 100 个输入)。技术细节以 cmets 的形式包含在代码中。

    library(shiny)
    
    # Simple GUI to let the user play with the app.
    ui <- fluidPage(
      actionButton("dev","dev"),
      actionButton("dev2","dev2")
    )
    
    # Here comes the serious business
    server <- function(input, output, session) {
      # First, I use reactiveValues (clear way to store values)
      rv <- reactiveValues(
        # And here is our main data frame
        df = data.frame(a = 0, b = 1)  
      )
     
      # Ok, let's get the magic begin ! R recognizes this in the current environment:
      makeReactiveBinding("rv$df")
      # Also works with things such as:
      #  makeReactiveBinding(sprint("rv$%s", "df"))
      # which opens the way to dynamic UI. 
      
      # Then, I get a way to catch my table from a reactive
      rdf <- reactive(rv$df)
    
      # And there, I only have to call for this reactive to get data.frame-related event
      observe(print(rdf()$b))
    
      # Here are some little ways to interact with the app
      # Notice the `<<-` assignment to store new values
      # Add values to df$a (expected behavior: print df$b at its value)
      observeEvent(input$dev, {
        rv$df$a <<- rv$df$a+1
      })
      # Add values to df$b (expected behavior: print df$b at its new value)
      observeEvent(input$dev2, {
          rv$df$b <<- rv$df$b+1
      })
    }
    
    shinyApp(ui, server)
    

    我希望这可能对 Shiny 的一些用户有所帮助。我发现这很容易实现,而且非常有用。

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 1970-01-01
      • 2017-07-27
      • 2013-07-08
      • 2018-12-29
      • 2020-11-20
      • 2018-01-23
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多