How to Make UI Respond to Reactive Values in for Loop

How to update reactive output inside a for loop in R shiny

With using invalidateLater you can get something closed to what you want. Not the shortest way to do it I think, but it may help you to find a better solution.

library(shiny)

# Basic interface
ui <- fluidPage(
actionButton("run", "Run"),
textOutput("textbox")
)

# Basic server with loop
server <- function(input, output, session) {

textvals <- reactiveVal(0)
active <- reactiveVal(FALSE)

output$textbox <- renderText({
textvals()
})

observe({
invalidateLater(1000, session)
isolate({
if (active()) {
textvals(textvals() + 1)
if (textvals() > 9) {
active(FALSE)
}
}
})
})

observeEvent(input$run, {
active(TRUE)
})
}

# Run the application
shinyApp(ui = ui, server = server)

By the way, reactive and for loops don't really get on well. This may help : https://gist.github.com/bborgesr/e1ce7305f914f9ca762c69509dda632e

Update shiny output from for loop inside observeEvent using reactiveValues

I rewrote your sever codes to make it working.

You cannot update UI in a loop as I already mentioned in the comment, it isn't how Shiny works. Use invalidateLater() to do something similar to a for loop.

And also, invalidateLater() doesn't work in observeEvent, so you need to write the loop logic in observe()

isolate() is used to prevent recursive triggering of the observer, so it only re-evaluate every 0.5 second based on invalidateLater(500)

server = function(input, output, session){
vars = reactiveValues(cc="",ct=0)
startSearch <- reactiveVal(FALSE)
startSearch <- eventReactive(input$searchgt,{
TRUE
})

observe({
req(startSearch())
if (isolate(vars$ct) < 10){
invalidateLater(500)
isolate({
vars$ct=vars$ct+1
vars$cc=paste('<b style="color:blue">',"Searching...",vars$ct,"</b>")
vars$busca = try(print("Something"),silent = T)
})
} else {
vars$cc=paste('<b style="color:red">',"Some warning.","</b>")
}

})

output$warngt = renderUI({HTML(vars$cc)})
}

Fill with User Input Reactive Dataframe with Loop

You can write the app as :

library(shiny)

ui <- fluidPage(
numericInput("In1", "Input 1", 60),
numericInput("In2", "Input 2", 100),
numericInput("In3", "Input 3", 100),

mainPanel(tableOutput("data"))
)

server <- function(input, output) {

data1 <- reactive({

data1 <- data.frame(x = 0, y = 1:60)

data1[1, 1] = (input$In1 * 4 * 12)/input$In3
data1[1, 2] = (input$In2 * 4 * 12)/input$In3

for (i in 2:60) {
data1[i,1] = ((input$In1 * 4 * 12)/input$In3) + data1[i-1, 1]
data1[i,2] = ((input$In2 * 4 * 12)/input$In3) + data1[i-1, 2]
}
return(data1)
})

#output$plot <- renderPlot({...})
output$data <- renderTable({data1()})
}

shinyApp(ui, server)

Sample Image

I haven't included any plot code but instead displayed the dataframe but you can also include the plot output the way you want.



Related Topics



Leave a reply



Submit