So, i created a program to optimize my marketing budget. As an input, the user need to set the total budget. I create this input variable as "cust_tot" in the Shiny UI code below:
ui <- fluidPage(
titlePanel("Budget Optimizer"),
sidebarLayout(
sidebarPanel(
numericInput("custo_tot", "Valor total do Investimento:", value = 3243452, min = 0),
actionButton("submit", "Otimizar")
),
mainPanel(
plotOutput("grafico_investimento_atual")
)
)
)
In order to get the data, i need to query, but the variable "custo_tot" (inputed by the user) is also going to be part of the query:
in my original code, it was something like that:
sql <- " query here "
sql = gsub("custo_rest_min_aux", custo_rest_min_aux, sql)
sql = gsub("custo_rest_max_aux", custo_rest_max_aux, sql)
sql = gsub("month_rest", sQuote(month_rest), sql)
sql = gsub("custo_tot", input$custo_tot, sql)
tb <- bq_project_query(projectid, sql)
df = bq_table_download(tb) %>% data.frame()
But i know that i cant simply use input$custo_tot because it shows the following error message:
Error in input$custo_tot :
Can't access reactive value 'custo_tot' outside of reactive consumer.
ℹ Do you need to wrap inside reactive() or observe()?
how should i deal with this?
As the error specifies, you cannot access the input
list unless you are inside a reactive consumer:
server <- function(input, output, session) {
sql <- reactive({
sql <- " query here "
sql = gsub("custo_rest_min_aux", custo_rest_min_aux, sql)
sql = gsub("custo_rest_max_aux", custo_rest_max_aux, sql)
sql = gsub("month_rest", sQuote(month_rest), sql)
sql = gsub("custo_tot", input$custo_tot, sql)
sql
})
}
This will make it a reactive so any time the inputs are updated this reactive will lazily update. Remember to use this reactive you need to call it like: sql()
.