虽然条件没有破坏

问题描述 投票:0回答:1

我在 R 中有以下代码,我相信它应该立即中断。相反,它会运行直到达到 number_of_retries 为止。但手动尝试“状态<- 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)
  }
r while-loop conditional-statements
1个回答
0
投票

这不是终止

while
循环的问题,而是
Sys.sleep(10)
给你一种错觉,认为
while
循环是无穷无尽的。

描述

将 R 表达式的执行暂停指定时间 间隔。

用法

Sys.sleep(time)

论点

time
暂停的时间间隔 执行时间,以秒为单位。

当你删除

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
}
© www.soinside.com 2019 - 2024. All rights reserved.