1

My question is similar to the following two:

Set global object in Shiny

Make object created inside one reactive object available to another in shiny

With the important difference that the object I want to create can't be defined in a single line. Therefore my understanding after checking this example is that I should use reactive({ }), But I'm getting the good old error "object of type 'closure' is not subsettable" and I can't figure out what am I doing wrong.

Specifically I'm trying to subset a large dataframe according to a set of variables the user would define playing with widgets. Then I would use this dataframe to perform different plots using renderPlot() independently but with the same data.

My code looks like:

# mydf is defined previously in global.R  

shinyServer(function(input, output) { 
  ##Subset  
   mydf2<- reactive({
    # by desired Altitude
    mydf<-mydf[c(mydf$Altitud>=input$Altitud[1], mydf$Altitud<=input$Altitud[2]),]

    # by desired Longitude
    mydf<-mydf[c(mydf$Longitud>=input$Longitud[1], mydf$Longitud<=input$Longitud[2]),]

    # by desired Latitud
    mydf<-mydf[c(mydf$Latitud>=input$Latitud[1], mydf$Latitud<=input$Latitud[2]),]
    mydf   
    })

  ## PCA   
  output$pca<- renderPlot({
                    plot(mydf2$eigenvect2, mydf2$eigenvect1)
                  }) 

 ## Other plotting 
 ...
})

The subsetting works perfectly well if I take it out from reactive and paste it inside output$pca<- renderPlot({ so this can't be the problem.

Help very much appreciated, this is my first shiny app.

Community
  • 1
  • 1
A.Mstt
  • 301
  • 1
  • 3
  • 15
  • Maybe I am silly but that way of subsetting with logical condition inside a `c()` does work? it shouldn't be done without `c` and instead by using logical operators like `&`? – SabDeM Jun 12 '15 at 16:33
  • 1
    After you have done this do your refer to mydf2 as `mydf2()`? It seems that your plot does not. So it should be `mydf2()$eigenvect2` and so on, never `mydf2$` – John Paul Jun 12 '15 at 16:34
  • Ahh brillinat, `mydf2()` works. Thanks @JohnPaul. Sorry if the question is silly, but could you please explain me what are the `()` doing? why `mydf2` is not just a "normal dataframe"? – A.Mstt Jun 12 '15 at 16:38
  • 1
    So here is the deal - the `reactive` is basically creating a function called `mydf2` that depends on `input$Alttitud` (and the other `input`s). So when you do `mdf2()$eigenvect` what you are really doing is running the `mydf2` function with the current inputs. Because it is a function, you need the `()` at the end. – John Paul Jun 12 '15 at 16:46

1 Answers1

0

The comments above are correct, here's how I usually do this:

     output$pca<- renderPlot({
                    plot_df <- mydf2()
                    plot(plot_df$eigenvect2, plot_df$eigenvect1)
                  })
Shorpy
  • 1,549
  • 13
  • 28