0
votes

all. I am very new to shiny and R but am trying to learn my way through it.

I could use your help learning how to pass information from the reactive function into renderPlot. I have successfully used my reactive function to build a data frame but, when I try and plot it in renderPlot using ggplot, the data is not available.

In renderPlot, I am getting the error that 'the object "product" does not exist'. Any thoughts?

server <- function(input, output) 
{
reactive_data <- reactive({

                finalData <- data.frame(ITEM_DESC=as.character(), revenue=double(), product=character())

                for (p in input$product_selection){

                    tempData <- orderData %>%
                        filter(grepl(p, ITM_DESC)) %>%
                        select(ITM_DESC, revenue) %>%
                        group_by(ITM_DESC) %>%
                        summarize(rev=sum(revenue))

                    tempData <- tempData %>% mutate(product = p)

                    if (dim(finalData)[1] == 0) {
                        finalData <- tempData
                    }
                    else{
                        finalData <- bind_rows(finalData, tempData)
                    }
                }

            })

# Render Plot
output$shinyOrders <- renderPlot(
                        ggplot(reactive_data()) +
                        geom_col(aes_string(x="product", y="rev")) +
                        theme_bw(18) +
                        theme(axis.text.x = element_text(angle = 90, hjust = 1))
                        )
}

# ---- Run App ----

shinyApp(ui, server)
1
for loops do not return anything. You need to return finalData explicitly. - r2evans

1 Answers

0
votes

for loops do not return anything. Observe:

(for (i in 1:3) i <- i+1)
# NULL
i
# [1] 4

I think that makes your solution (untested):

server <- function(input, output) {
  reactive_data <- reactive({

    finalData <- data.frame(ITEM_DESC=as.character(), revenue=double(), product=character())

    for (p in input$product_selection){

      tempData <- orderData %>%
        filter(grepl(p, ITM_DESC)) %>%
        select(ITM_DESC, revenue) %>%
        group_by(ITM_DESC) %>%
        summarize(rev=sum(revenue))

      tempData <- tempData %>% mutate(product = p)

      if (dim(finalData)[1] == 0) {
        finalData <- tempData
      }
      else{
        finalData <- bind_rows(finalData, tempData)
      }
    }

    return(finalData) # <--------- you need this

  })

  # Render Plot
  output$shinyOrders <- renderPlot(
    ggplot(reactive_data()) +
      geom_col(aes_string(x="product", y="rev")) +
      theme_bw(18) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1))
  )
}

# ---- Run App ----

shinyApp(ui, server)