Reputation: 529
I want to use a dataframe that is generated based off an input in multiple outputs. Is there a way I can generate this output just once versus doing it for every output?
For example,The user will generate give their input such as a date
dateRangeInput("date", label = "Delivered Date Range: ", start = ld, end = hd)
I will then use that date range input in multiple outputs. However, two outputs require the same query to get the same dataframe using that input.
output$p1 <- renderPlotly({
q1 <- "
SELECT *
FROM table
WHERE date > '"
q2 <- input$date[1]
q3 < "'"
p1_df <- sqlQuery(DS, q)
plot_ly(data = p1_df, x = ~x, y = ~y)
})
output$p2 <- renderPlotly({
q1 <- "
SELECT *
FROM table
WHERE date > '"
q2 <- input$date[1]
q3 < "'"
p2_df <- sqlQuery(DS, q)
plot_ly(data = p2_df, x = ~x, y = ~y)
})
Is there a way in Shiny that I only have to run this query once as to make my app more efficient?
Thanks
Upvotes: 3
Views: 1886
Reputation: 196
You can move the query into reactive function (function inside "server" part of the app):
sqlData <- reactive({
q1 <- "
SELECT *
FROM table
WHERE date > '"
q2 <- input$date[1]
q3 < "'"
p1_df <- sqlQuery(DS, q)
return(p1_df)
})
and then just call it inside renderPlotly:
output$p1 <- renderPlotly({
p1_df <- sqlData()
plot_ly(data = p1_df, x = ~x, y = ~y)
})
output$p2 <- renderPlotly({
p2_df <- sqlData()
plot_ly(data = p2_df, x = ~x, y = ~y)
})
Upvotes: 2