[英]How to get a reactive data.frame in a shiny application
我想知道如何讓我的 shiny 應用程序對對 data.frame 的任何修改做出反應。 這在很多方面都很有用。 就像是:
[server part]
rv <- reactiveValues(
df <- data.frame(...)
)
observeEvent(rv$df, {
...
})
這是我想出的一個解決方案的例子。 請注意,這只是一個用例(沒有模塊)。 我會告訴你,我成功地將它應用於更復雜的應用程序(> 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 的一些用戶有所幫助。 我發現這很容易實現並且非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.