rshinyrbindinfinite-recursion

R Shiny error with rbind to compile results from a loop : error evaluation nested too deeply: infinite recursion


I try to compile results obtained from a loop in a dataframe, adding the results of each iteration to the dataframe using rbind (here, this is a simplified example). The code works without problem in R, but in R shiny it leads to an infinite recursion problem:

"error: evaluation nested too deeply: infinite recursion / options(expressions=)?"

I tried several solutions and searched in the forums but could not manage to find exactly the same question. If someone could help me it would be great !!!

Thanks !

library(shiny)

# Define the ui
ui <- fluidPage(

  # Sidebar with a slider input 
  sidebarLayout(
    sidebarPanel(
       sliderInput("add",
                  "Number to add:",
                  min = 2,
                  max = 20,
                  value = 10)
    ),

    mainPanel(
      tableOutput("view")
    )
  )
)


# Define the server code
server <- function(input, output, session){

  results = reactive({data.frame(i=NA, A=NA)[-1,]})

  for(j in 1:10){

      res_j   =  reactive({data.frame(i=j, A=j+input$add)})
      results =  reactive({rbind(results(), res_j())})
  }

  output$view <-renderTable(results())

}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

Solution

  • Maybe something like this:

    library(shiny)
    
    # Define the ui
    ui <- fluidPage(
    
      # Sidebar with a slider input 
      sidebarLayout(
        sidebarPanel(
          sliderInput("add",
                      "Number to add:",
                      min = 2,
                      max = 20,
                      value = 10)
        ),
    
        mainPanel(
          tableOutput("view")
        )
      )
    )
    
    
    # Define the server code
    server <- function(input, output, session){
    
      results = reactiveValues()
    
      observeEvent(input$add, {
        results$df=data.frame(i=NA, A=NA)[-1,]
        for(j in 1:10){
          res_j   = data.frame(i=j, A=j+input$add)
          results$df =  rbind(results$df, res_j)
        }
      })
    
      output$view <-renderTable(results$df)
    
    }
    
    # Return a Shiny app object
    shinyApp(ui = ui, server = server)