lapply循环可根据经过的时间跳到下一个迭代

时间:2018-07-26 01:32:12

标签: r lapply

我想创建一个lapply循环,当当前迭代需要60秒以上才能完成时,该循环将跳至下一个迭代。该脚本包含一个trycatch来处理函数可能返回的错误。我尝试使用withTimeout()失败。

flex-direction: column

1 个答案:

答案 0 :(得分:2)

您已经翻转了withTimeouttryCatch

这是一个基于以下简单函数的最小可重复示例:我们有一个data.frame次,delay次(以秒为单位);然后,我们遍历delay次,并使用Sys.sleep将系统暂停多达几秒钟。

如果执行时间超过2秒,我们使用withTimeout跳过一步。

# Delay times from 1 to 10 seconds in 1 second steps
df <- data.frame(delay = seq(1:10))

library(R.utils)
lst <- lapply(1:nrow(df), function(i) {
    cat(sprintf("Processing row %i/%i...", i, nrow(df)))
    tryCatch(
        withTimeout( {
            Sys.sleep(df$delay[i]);
            cat("[Done]\n") },
            timeout = 2),
        TimeoutException = function(ex) cat("[Skipped due to timeout]\n"))
})
#Processing row 1/10...[Done]
#Processing row 2/10...[Skipped due to timeout]
#Processing row 3/10...[Skipped due to timeout]
#Processing row 4/10...[Skipped due to timeout]
#Processing row 5/10...[Skipped due to timeout]
#Processing row 6/10...[Skipped due to timeout]
#Processing row 7/10...[Skipped due to timeout]
#Processing row 8/10...[Skipped due to timeout]
#Processing row 9/10...[Skipped due to timeout]
#Processing row 10/10...[Skipped due to timeout]

请注意如何将withTimeout包装在tryCatch中以捕获(默认)超时错误,并在不终止lapply循环的情况下打印自定义错误消息。