readline equivalent behavior in Shiny

Let's consider the following function:

foo <- function(n){
  out <- double(n)
  for( i in 1:n ){
    # Here an external algorithm is run. We need to make a decision regarding its possible outputs.
    ANSWER <- readline("Provide number and press Enter: ")
    out[i] <- as.numeric( ANSWER )
  }
  return(out)
}

When providing 5 as an input, inner loop has 5 iterations. Each time the user has to provide a particular number. As a result we would have a vector with 5 elements. The question is how to emulate this behaviour in Shiny. My suggestion is below:

foo <- function(input, session){
  out <- double(input$n)
  for( i in 1:input$n ){
    # Force to stop a loop
    # Provide a decision
    out[i] <- ( input$decision )
    # Press Enter
  }
  return(out)
}

ui <- fluidPage(
  numericInput( "n", "nIter", value = 5, min = 1, max = 10, step = 1),
  numericInput( "decision", "Provide number and press Enter", value = 1, min = 1, max = 10, step = 1),
  actionButton("enter","Enter"),
  verbatimTextOutput("out")
)

server <- function(input, output, session){
  out <- reactive({
    input$n
    foo( input, session )
  })
  output$out <- renderPrint({
    out()
  })
}

shinyApp(ui = ui, server = server)

The problem is that, now an entire function is executed with all iterations and output vector has the same values.

Best
Chris

I recommend you study how to make dynamic ui, uiOutput()/renderUI
The solution would be to use input$n to produce n number of numericInputs dynamically.

Thank you for the answer. However it is an important requirement to behave like readline. Readline allows to communicate with the foo function while running. I have to provide a number and use this value during the next iteration, without escaping the function. I have an external foo function and I need to put the input from the Shiny into a certain state of my function. Maybe there is a functionality forces the user to make a decision, i.e. observeEvent() and eventReactive() are triggered by input$click or changes in reactiveValue(). I need to observe an event inside my function (to be precise force to observe), I need to stop the current iteration and wait for the decision.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.