Home > OS >  R loop checking condition X times and break if not met
R loop checking condition X times and break if not met

Time:11-09

I'd like to create kind of dependency between R and database and for that I'm trying to create a loop which is checking if a date in one column from a database is equal to today's date, if yes then run main statement, if not wait 5mins and try again (max 24 times) then break. I'm stucked with the latter, if someone could advice that would be helpful, thanks!

if(lubridate::date(table$db_date) == Sys.Date()){
  print(1) 
} else {
  Sys.sleep(300)
  # and repeat the loop 24 times until statement is TRUE, if not then break
}

CodePudding user response:

If you have an upper limit for the number of iterations, you should use a for loop:

for (i in seq_len(24)) {
  if(lubridate::date(table$db_date) == Sys.Date()){
    print(1) 
    break
  } else {
    Sys.sleep(300)
  }
}

CodePudding user response:

Very primitive but maybe something like this:

i=1 # establish global variable
while (T) {
  
  if(lubridate::date(table$db_date) == Sys.Date()){
  print(1) 
  # break
  } 

  if(i < 24 & lubridate::date(table$db_date) != Sys.Date()) { # check both statements
    i <<- i 1 # update global variable
    Sys.sleep(0.1) # and repeat the loop 24 times until statement is TRUE, if not then break
  }

  else{break}
}
  • Related