Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set global object in Shiny

Tags:

r

subset

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?

like image 865
Waldir Leoncio Avatar asked Jul 16 '13 18:07

Waldir Leoncio


People also ask

Is shiny easy to learn?

Along with Shiny elements, you can use HTML elements to stylize your content in your application. In my opinion, R Shiny is very easy to learn despite how powerful the tool is. If you're working on a side project or looking to add something to your portfolio, I highly recommend trying it out.

What is a global R file?

For the uninitiated, global. R is a separate file that's really useful when you're deploying to a server because it is run only once when the application is run the first time and then will serve its contents to any applications. Its contents is also available to ui.

What is session in R shiny?

Description. Shiny server functions can optionally include session as a parameter (e.g. function(input, output, session) ). The session object is an environment that can be used to access information and functionality relating to the session.


1 Answers

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.

like image 149
Jake Burkhead Avatar answered Nov 21 '22 12:11

Jake Burkhead