yahooligan8
yahooligan8

Reputation: 41

Calling variables from reactive functions inside render*()

I have a server.R file in the following form:

server.R

shinyServer(


  function(input, output, session) {    

    mydata<- reactive({
              df<- dataframe1
              variable1
              variable2
              list(df, variable1, variable2)
             
    })

  output$plot<- renderPlot({  

   p<-ggplot(mydata()$df, aes(y=V8, x = 1:nrow(mydata()$df), fill = V8))
   print(p)
   
   })
 })

My issue is that the call to ggplot, while it seems to recognize mydata$df(), it returns the error

Error in nrow(mydata()$df) : could not find function "mydata".

I am not sure where my syntax is wrong. Can anyone shed some light? Thanks!

Upvotes: 1

Views: 1700

Answers (2)

MrFlick
MrFlick

Reputation: 206606

I'm going to shamless steal most of @charles code, but i think the problem in this case is actually your aes(). This seems to work

runApp(
  list(ui = basicPage(
    h1('Demo Shiny'),
    plotOutput("plot")
  )

  ,server = function(input, output) {
    mydata <- reactive({
            df <- data.frame( V8=sample(1:4, 20, replace=T))
            list(df=df, variable1=1, variable2=2)
    })

    output$plot = renderPlot({
      p<-ggplot(mydata()$df, aes(x=seq_along(V8), y = V8)) + geom_point()
      print(p)
    })
  })
)

The problem was referring to variables in your aes that were not in your data.frame that you passed to ggplot2. Here by making sure to include a proper variable from the df, we seem to be fine.

Upvotes: 0

cdeterman
cdeterman

Reputation: 19970

To my knowledge, reactive shiny objects don't play well with lists. As it appears you aren't using 'variable1' and 'variable2' just omit them and just do the dataframe (which I assume has been made globally accessible and isn't imported?). It also could simply be calling the reactive before the ggplot call, but I err towards simplicity if not using those extra variables. A very quick example:

runApp(
  list(ui = basicPage(
    h1('Demo Shiny'),
    plotOutput("plot")
  )

  ,server = function(input, output) {
    mydata <- reactive({
      dataframe1 <- data.frame(cond = rep(c("A", "B"), each=10),
                               xvar = 1:20 + rnorm(20,sd=3),
                               yvar = 1:20 + rnorm(20,sd=3))
      dataframe1
    })

    output$plot = renderPlot({
      df <- mydata()
      p<-ggplot(df, aes(x=xvar, y = yvar)) + geom_point()
      print(p)
    })
  })
)

Upvotes: 1

Related Questions