首页 > 解决方案 > 如何在闪亮的应用程序中获取响应式 data.frame

问题描述

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

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

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

标签: rshinyreactive

解决方案


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

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 的一些用户有所帮助。我发现这很容易实现并且非常有用。


推荐阅读