简体   繁体   English

如何使用R在for循环中实现tryCatch()

[英]How to implement tryCatch() in for loop using R

I've written R code using for() loop which reads some queries stored in R column of excel sheet, hits the server and saves the retrieved response in a text file. 我已经使用for()循环编写了R代码for()该循环读取了存储在excel工作表R列中的一些查询,命中服务器并将检索到的响应保存在文本文件中。 The code runs fine until the server responds with an error the loop execution stops. 该代码运行良好,直到服务器响应错误并停止循环执行为止。 I tried implementing tryCatch() within my code but couldn't implement well. 我尝试在我的代码中实现tryCatch() ,但实现不好。

Please help me implementing tryCatch() in my code which can save error in the different file and can continue the for() loop. 请帮助我在代码中实现tryCatch() ,这样可以将错误保存在其他文件中,并可以继续for()循环。

Code: 码:

for (i in 1:R_column_len){
        R_column_data <- (file_data[[6]][i])
      a <- eval(parse(text = R_column_data))
      write.table(a,file = sprintf("C:/Results/F_Query_Prod_%s.txt", i))
    }

Maybe this illustrates the general idea 也许这说明了总体思路

library(futile.logger)

f <- function() {
    for (i in 1:10) {
        tryCatch({
            if (i %% 3 == 0)
                stop("my bad")
            ## normal behavior
            flog.info("i = %d", i)
        }, error = function(e) {
            ## error behavior
            flog.error("oops, i = %d: %s", i, conditionMessage(e))
        })
    }
}

producing output 产生产出

> f()
INFO [2018-10-25 15:50:05] i = 1
INFO [2018-10-25 15:50:05] i = 2
ERROR [2018-10-25 15:50:05] oops, i = 3: my bad
INFO [2018-10-25 15:50:05] i = 4
INFO [2018-10-25 15:50:05] i = 5
ERROR [2018-10-25 15:50:05] oops, i = 6: my bad
INFO [2018-10-25 15:50:05] i = 7
INFO [2018-10-25 15:50:05] i = 8
ERROR [2018-10-25 15:50:05] oops, i = 9: my bad
INFO [2018-10-25 15:50:05] i = 10

Use features of futile.logger to append to file rather than the console, and to record only errors 使用futile.logger的功能附加到文件而不是控制台,并仅记录错误

fl <- tempfile()
flog.appender(appender.file(fl))
flog.threshold(ERROR)
f()

the result is 结果是

> readLines(fl)
[1] "ERROR [2018-10-26 06:28:37] oops, i = 3: my bad"
[2] "ERROR [2018-10-26 06:28:37] oops, i = 6: my bad"
[3] "ERROR [2018-10-26 06:28:37] oops, i = 9: my bad"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM