gpt4 book ai didi

r - R:在foreach%dopar%中显示错误和警告消息

转载 作者:行者123 更新时间:2023-12-04 09:36:42 25 4
gpt4 key购买 nike

对于使用foreach()%dopar%进行并行处理,我是新手,但我对它如何处理错误或警告存在一些疑问。

  • 当我将try()与foreach()%dopar%中的自定义错误消息一起使用时,“本地”错误消息不显示:
    test <- function(x) {
    if (x==2) "a"/2
    }

    foreach(i=1:3) %dopar% {
    tryout <- try(test(i))
    if (class(tryout)=="try-error") print("Error!")
    }

    在这种情况下,“ native ”错误消息:Error in "a"/2 : non-numeric argument to binary operator不显示,并且仅会打印来自try()错误捕获的Error!。但是,当不使用foreach()%dopar%时,将同时打印这两个错误消息。那么如何使两个错误消息都显示出来呢?
  • 在上述情况下,如果有警告,则无论是否附加错误,都不会打印警告消息,例如,使用与上面相同的foreach()块和下面的test():
    test <- function(x) {
    if (x==2) warning("Warning!")
    }

    那么如何显示警告呢?

  • p.s.我发现,如果仅在%dopar%中使用try(test(i)),则将显示“ native ”错误消息和警告,但我确实希望在实际情况中包括自己的错误消息。我也尝试使用 tryCatch()而不是 try(),但是并不能解决问题。

    谢谢!

    最佳答案

    我认为问题出在您的错误处理以及对dopar的误解。首先,将dopar更像是一个函数。默认情况下,它必须将对象作为列表返回给用户(它收集每个工作程序的所有输出,而foreach函数收集这些输出并将其返回使用,请参见下面的“output_list”)。

    您还可以设置.errorhandling ='pass',它将错误返回给输出对象(请注意,仅当.combine ='list'时才有效)。 .errorhandling的工作方式如下:

    .errorhandling specifies how a task evaluation error should be handled. If the value is "stop", then execution will be stopped via the stop function if an error occurs. If the value is "remove", the result for that task will not be returned, or passed to the .combine function. If it is "pass", then the error object generated by task evaluation will be included with the rest of the results. It is assumed that the combine function (if specified) will be able to deal with the error object. The default value is "stop".



    这是一个如何在foreach内部设置tryCatch的示例。请注意,错误现在存储在output_list中。
    output_list = foreach(i=1:3, .errorhandling='pass') %dopar% {
    result <- tryCatch({
    object_that_doesnt_exist[i]},
    warning = function(war) {
    return('a warning')},
    error = function(err) {
    return('an error')},
    finally = {
    return('other things')
    }) # END tryCatch

    return(result) # return your result to outputlist
    }

    output_list

    关于r - R:在foreach%dopar%中显示错误和警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262612/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com