Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

r - Set global object in Shiny

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)
   })
})

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)
  })
})

What did I do wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
  })
})

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...