在 Shiny 中设置全局对象 [英] Set global object in Shiny

查看:28
本文介绍了在 Shiny 中设置全局对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 server.R 文件:

Let's say I have the following server.R file in shiny:

shinyServer(function(input, output) {
  output$plot <- renderPlot({
    data2 <- data[data$x == input$z, ]  # subsetting large dataframe
    plot(data2$x, data2$y)
  })
   output$table <- renderTable({
     data2 <- data[data$x == input$z, ]  # same subset. Oh, boy...
     summary(data2$x)
   })
})

为了不必在每次渲染调用中运行 data2 <- data[data$x == input$z, ] 我该怎么做?如果我执行以下操作,我会收到'closure' 类型的对象不可子集化"错误:

What can I do in order to not have to run data2 <- data[data$x == input$z, ] within every render call? If I do the following, I get a "object of type 'closure' is not subsettable" error:

shinyServer(function(input, output) {
  data2 <- reactive(data[data$x == input$z, ])
  output$plot <- renderPlot({
    plot(data2$x, data2$y)
  })
  output$table <- renderTable({
    data2 <- data[data$x == input$z, ]
    summary(data2$x)
  })
})

我做错了什么?

推荐答案

data2 是一个返回您要查找的子集的函数.所以你需要调用 data2 并将输出保存到某个变量然后你可以绘制/总结各个列

data2 is a function which returns the subset you are looking for. So you need to call data2 and save the output to some variable then you can plot/summarize the various columns

## data should be defined somewhere up here or in global.R

shinyServer(function(input, output) {
  data2 <- reactive(data[data$x == input$z, ])

  output$plot <- renderPlot({
    newData <- data2()
    plot(newData$x, newData$y)
  })

  output$table <- renderTable({
    newData <- data2()
    summary(newData$x)
  })
})

如果您还没有,我建议您通读http://rstudio.github.io/shiny/tutorial/#welcome.反应性页面很好地解决了这个问题.

If you haven't already, I recommend reading through http://rstudio.github.io/shiny/tutorial/#welcome. The page on reactivity addresses this question fairly well.

这篇关于在 Shiny 中设置全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆