代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

“lappy”是否可以在“timeout”约束下返回部分处理结果?

  •  1
  • Omry Atia  · 技术社区  · 6 年前

    我有一些代码需要很长时间才能执行。因此我使用 R.util withTimeout . synthax是这样的:

    res <- withTimeout({
      v1 %>% mutate(Output = unlist(lapply(as.list(data.frame(t(v1))),function(x) 
      SomeFunction(x))))
    }, timeout = 2, onTimeout = "warning")
    

    在我的密码里, v1 是一个包含多行的数据帧,函数按行运行(使用 lapply

    1 回复  |  直到 6 年前
        1
  •  1
  •   Zheyuan Li    6 年前

    出于好奇,我试了以下方法,似乎效果不错。

    ## an example data frame of 1000 columns
    ## `lapply` will loop a function over it column by column
    x <- data.frame(matrix(sample.int(2, 2 * 1000, TRUE), 2, 1000))
    
    ## actually a wrapper function of your `SomeFunction`
    ## it takes an additional `time_limit` (in seconds)
    ## is also access a GLOBAL variable `elapsed_time`
    f <- function (x, time_limit) {
      if (elapsed_time < time_limit) {
        t1 <- proc.time()[[3]]
        z <- tabulate(sample(x, 1e+5, TRUE))  ## an arbitrary example function here
        t2 <- proc.time()[[3]]
        elapsed_time <<- elapsed_time + (t2 - t1)  ## note the `<<-`
        } else {
        z <- NULL
        }
      z
      }
    
    elapsed_time <- 0                  ## elapsed time counter (in global environment)
    oo <- lapply(x, f, time_limit = 2) ## 2 seconds time limit
    
    elapsed_time
    #[1] 2.002
    
    sum(sapply(oo, is.null))
    #[1] 693
    

    所以在我的笔记本电脑上,迭代在(1000-693)=307轮之后终止。 lapply 仍然返回长度为1000的列表,但只有前307个元素保留处理结果,而其余693个条目保留 NULL

    实际上,这是一个很好的例子 <<- 会有用的。