[英]Shiny in R: How to properly use reactive, observe and renderUI?
我的代碼有問題。 每當我點擊一個按鈕時,我的情節(用ggvis構建)就會顯示出來,但會立即消失。 由於我的代碼很長,下面的代碼重現了我的問題。 我想在我的渲染函數中重用反應數據幀test0,我想這正是導致我的問題的原因。 但這對我來說至關重要。 三個步驟(反應,觀察,渲染)與我的代碼相同。 我非常感謝你的幫助!
server.R
library(shiny)
library(ggvis)
library(dplyr)
data(mtcars)
shinyServer(function(input, output) {
test0 <- reactive({
df <- mtcars %>% select(mpg, wt)
(input$NextCounter + 1)*df
})
observe({
df <- test0()
if (!is.null(df)) {
ggvis(df, x = ~wt, y = ~mpg) %>% bind_shiny("plotggvis")
}
})
output$test1 <- renderUI({
df <- test0()
ggvisOutput("plotggvis")
})
})
ui.R
庫(閃亮)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("NextCounter", "Next")
),
mainPanel(
uiOutput("test1")
)
)
))
這個適合我
library(shiny)
library(ggvis)
library(dplyr)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("NextCounter", "Next")
),
mainPanel(
ggvisOutput("plotggvis")
)
)
))
server <- shinyServer(function(input, output) {
data(mtcars)
test0 <- reactive({
df <- mtcars %>% select(mpg, wt)
(input$NextCounter + 1)*df
})
my_graph <- reactive({
df <- test0()
ggvis(df, x = ~wt, y = ~mpg)
})
my_graph %>% bind_shiny("plotggvis")
})
})
shinyApp(ui = ui, server = server)
您不需要在UI中使用ggvisOutput
來解決您的問題。 實際上,代碼中的問題是在觀察者中有bind_shiny
函數,每次test0
數據發生變化時都會再次執行。 預計只會綁定你的ggvis一次,否則它會出現並立即消失的行為。 此外,ggvis的一個重要特性是在數據更改時有一個很好的轉換,因此每次數據更改時都不需要創建ggvis對象,只需確保在UI中只綁定一次ggvis對象。
下面是代碼的修改版本,用於解決您的問題並顯示數據的動畫過渡。
library(shiny)
library(ggvis)
library(dplyr)
data(mtcars)
ui <- fluidPage(fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("NextCounter", "Next")
),
mainPanel(
uiOutput("test1")
)
)
))
server <- function(input, output) {
test0 <- reactive({
input$NextCounter
df <- mtcars %>% select(mpg, wt)
df[sample(nrow(df),nrow(df)/2), ]
})
output$test1 <- renderUI({
# bind the ggvis only once
test0 %>% ggvis(x = ~wt, y = ~mpg) %>% bind_shiny("plotggvis")
ggvisOutput("plotggvis")
})
}
shinyApp(ui, server)
您還可以通過將ggvis
放在反應式表達式中來使用輸入小部件修改一些ggvis參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.