mercredi 27 avril 2016

How to modularise reactive output in Shiny (that includes if statement)?

Up until recently, I had been repeating the same reactive statements within each output of the server object.

server <- function(input, output) {
 output$MeanResult <- renderText({
   if(input$Posi != "All"){
     ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   mean(ProjDt[[input$Metric]])
 })
 output$hist <- renderPlot({
   if(input$Posi != "All"){
     ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   hist(ProjDt[[input$Metric]])
 })
} 

This seems to produce the desired result but I would like to avoid duplicating the reactive part of each output.

I therefore attempted to 'modularise' the reactive part of the code before passing it to the output statements such that:

server <- function(input, output) {
 ProjDt <- reactive({
   if(input$Posi != "All"){
      ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   ProjDt <- ProjDt[[input$Metric]]
 })
 output$MeanResult <- renderText({
   mean(ProjDt())
 })
 output$hist <- renderPlot({
   hist(ProjDt())
 })
}

I've played around with it quite a lot but I can't get the desired result. The main error I get is that 'object of type 'closure' is not subsettable'.

I'm relatively new to Shiny so I feel like I'm missing something quite fundamental.

What do I need to do get the modularised reactive output to work?

Aucun commentaire:

Enregistrer un commentaire