繁体   English   中英

R中有光泽:如何正确使用反应,观察和渲染?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM