'How to avoid error in the output (render) of a reactive object that will still be created in shiny?
I'm not able to solve the following problem with shiny app: a reactive object will be created after some procedures. In the middle of the way there is an actionButton, which depending on the option, one or another calculation will be made. This object will be used in an output. The problem is that when executing the code an error occurs in the output, saying that the function (reactive) was not found. This function should be executed only after the object is created. I've tried everything. observe, observeEvent (with some crazy things) and nothing worked. Below I tried to create a minimal reproducible code that would portray my problem.
ui <- fluidPage(
numericInput('num','Put a number!',value=1),
uiOutput("datas")
)
server <- function(input, output) {
observe({
if(input$num==2){
num <- reactive({
nume <- input$num + 2
nume
})
showModal(modalDialog(
title = "Menssagem importante",
"Escolha uma das opções abaixo",
footer = tagList(
actionButton("sim","Sim"),
actionButton("nao","Não")
)
))
observeEvent(input$sim,{
newnum <- NULL
for(i in 1:20){
newnum[i] <- num()+1
}
newnum
})
observeEvent(input$nao,{
newnum <- NULL
for(i in 1:20){
newnum[i] <- num()+5
}
newnum
})
resfinal <- reactive({
value <- newnum()^2 + log(10)
value
})
}
})
output$datas <- renderPrint({ resfinal() })
}
shinyApp(ui, server)
I appreciate if someone gives me some light.
Solution 1:[1]
I am not sure if I get it correctly but maybe it can be helpful:
ui <- fluidPage(
numericInput('num', 'Put a number!', value = 1),
uiOutput("datas")
)
server <- function(input, output) {
num_react <- reactiveVal()
newnum_react <- reactiveVal()
observe({
if(input$num == 2){
num_react(input$num + 2)
showModal(
modalDialog(
title = "Mensagem importante",
"Escolha uma das opções abaixo",
footer = tagList(
actionButton("sim", "Sim"),
actionButton("nao", "Não")
)
)
)
}
})
observeEvent(input$sim, {
newnum <- numeric(20)
for(i in 1:20) newnum[i] <- num_react() + 1
newnum_react(newnum)
removeModal()
})
observeEvent(input$nao, {
newnum <- numeric(20)
for(i in 1:20) newnum[i] <- num_react() + 5
newnum_react(newnum)
removeModal()
})
resfinal <- reactive({
value <- newnum_react()^2 + log(10)
value
})
output$datas <- renderPrint({
req(resfinal())
resfinal()
})
}
shinyApp(ui, server)
The idea is to use reactiveVal to store the values you need and then you can use req() to avoid the error when the object is not available yet.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Douglas Mesquita |
