【问题标题】:Make object created inside one reactive object available to another in shiny [duplicate]使在一个反应​​性对象中创建的对象以闪亮的方式可供另一个反应性对象使用[重复]
【发布时间】:2013-10-28 07:20:18
【问题描述】:

我有一个闪亮的应用程序,我在其中定义了一个基于滑块的对象并从中创建一个data.frame。这用于创建一个图,我想在其下方包含一个汇总表。我的问题是必须在反应对象内部定义绘图才能根据滑块进行更新,但我发现当我尝试访问对象以在 不同的 反应对象中打印摘要时,没找到。

我不想为了让对象进入另一个反应对象而两次运行相同的计算代码。我最初的两个想法:

  • 我尝试在第一个反应对象中使用save(object, file = "..."),然后在第二个反应对象中使用load(file = "..."),但它没有更新。
  • 我想在我的反应式plotOutput 定义之外定义我的对象,但我很确定当用户输入更改时它不会更新;它将保持初始 input 对象默认设置的值。

好吧,只是继续尝试后一种想法,但它甚至没有走那么远:

  • 我把它放在shinyServer(...) 之前,它无法生成数据,因为我的调用依赖于input,并且那时它不知道input
  • 我把它放在shinyServer(...) 之后但在renderPlot(...) 之前尝试为所有输出对象创建一个“全局可用”对象,它责备我试图做一些在反应之外使用input 的事情功能。

这里有一个例子来说明,修改自 Shiny 的"Hello Shiny!" example:

ui.R

library(shiny)

# Define UI for application that plots random distributions 
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarPanel(
    sliderInput("obs", 
                "Number of observations:", 
                min = 1,
                max = 1000, 
                value = 500)
  ),

  # Show a plot of the generated distribution
  mainPanel(
    plotOutput("distPlot"),
    tableOutput("summary")
  )
))

server.R

library(shiny)

# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {

  output$distPlot <- renderPlot({

    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })

  output$summary <- renderTable({
    #dist <- rnorm(input$obs)
    summary <- table(data.frame(cut(dist, 10)))
  })
})

如果按原样运行,cut 将抛出错误,因为它不知道 dist。如果您取消注释我们重新定义 dist 的行,就像在 plotOutput 中所做的那样,那么它将起作用。

这是一个简单的代码——我的代码比较复杂,我真的不想为了让另一个响应式输出知道相同的结果而运行两次。

建议?

【问题讨论】:

  • 投票结束。在我提出问题后,我尝试使用更好的术语进行搜索(称我正在寻找“全局对象”而不是上面的外行短语),并找到了我认为可以回答问题的重复项。

标签: r output rstudio shiny


【解决方案1】:

只是根据other question I consider mine to have duplicated 中的答案充实上面的示例,代码如下所示:

library(shiny)

# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {

  dist <- reactive(rnorm(input$obs))

  output$distPlot <- renderPlot({

    # generate an rnorm distribution and plot it
    dist <- dist()
    hist(dist)
  })

  output$summary <- renderTable({
    dist <- dist()
    summary <- table(data.frame(cut(dist, 10)))
  })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2017-07-03
    • 2019-03-23
    • 2014-11-12
    • 2018-07-16
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多