Reputation: 346
I wonder how I could get my shiny app react to any modification brought to a data.frame. This can be useful in many ways. Something like:
[server part]
rv <- reactiveValues(
df <- data.frame(...)
)
observeEvent(rv$df, {
...
})
Upvotes: 0
Views: 1038
Reputation: 346
Here is an example of a soluce I came up with. Please note that this is only one use case (without modules). I'll let you know that I successfully adapted it on a more complex app (> 100 inputs). Technical details are included into the code as comments.
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)
I hope this might help some users of Shiny. I find this quite easy and quick to implement and really useful.
Upvotes: 2