Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While condition does not break

I have the following code in R, and I believe it should break immediately. Instead it runs until number_of_retries is reached. But trying it manually "status <- run_request_and_writedb()" makes status TRUE, and is.null(status ) evaluates to FALSE, which should break the while loop if not both conditions are met. What am I missing here, or do I fundamentally misunderstand while conditions?

run_request_and_writedb <- function() {
      return(TRUE)
}

  ## Try the function a few times
  # return value is null
  status <- NULL
  # number of attempts at start
  attempt <- 1
  number_of_retries <- 3
  
  while( is.null(status) && attempt <= number_of_retries ) {
    try(
      status <- run_request_and_writedb()
    )
    attempt <- attempt + 1
    Sys.sleep(10)
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s not a matter of terminating the while loop, but Sys.sleep(10) gives you the illusion that the while loop is endless (unless you are sufficiently patient and wait for 10 seconds).

Description

Suspend execution of R expressions for a specified time
interval.

Usage

Sys.sleep(time)

Arguments

time The time interval to suspend
execution for, in seconds.

When you remove Sys.sleep(10), you can see that your code exits the loop

## Try the function a few times
# return value is null
status <- NULL
# number of attempts at start
attempt <- 1
number_of_retries <- 3

while (is.null(status) && attempt <= number_of_retries) {
    status <- run_request_and_writedb()
    attempt <- attempt + 1
}

or add break immediately before Sys.sleep(10)

## Try the function a few times
# return value is null
status <- NULL
# number of attempts at start
attempt <- 1
number_of_retries <- 3

while (is.null(status) && attempt <= number_of_retries) {
    status <- run_request_and_writedb()
    attempt <- attempt + 1
    break
    Sys.sleep(10)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading