如果在R中失败,则移至下一个代码行

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

我不知道如何在Google上进行搜索。我有彼此独立的行代码-假设一行由于某种原因而失败,那么脚本的其余部分将不会继续。如何使其继续?

例如:

library(RODBC)
library(sqldf)
myconn<-odbcConnect("production")

#行1:sqlQuery(myConn,“ exec sp_v_table_1”)

#line 2:sqlQuery(myConn,“ exec sp_v_table_2”)

也由于第1行失败而失败

此外,我怎么知道某个代码行-例如:

sqlQuery(myConn,"exec sp_v_table_3") 

已成功通过但未失败?

sql r rodbc sqldf
3个回答
2
投票

您可以使用tryCatch块,您有参考文献here

这里有一个使用它进行请求处理的示例:

urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",


   "xxxxx"
)

readUrl <- function(url) {
    out <- tryCatch(
        {
            # Just to highlight: if you want to use more than one 
            # R expression in the "try" part then you'll have to 
            # use curly brackets.
            # 'tryCatch()' will return the last evaluated expression 
            # in case the "try" part was completed successfully
        message("This is the 'try' part")

        readLines(con=url, warn=FALSE) 
        # The return value of `readLines()` is the actual value 
        # that will be returned in case there is no condition 
        # (e.g. warning or error). 
        # You don't need to state the return value via `return()` as code 
        # in the "try" part is not wrapped insided a function (unlike that
        # for the condition handlers for warnings and error below)
    },
    error=function(cond) {
        message(paste("URL does not seem to exist:", url))
        message("Here's the original error message:")
        message(cond)
        # Choose a return value in case of error
        return(NA)
    },
    warning=function(cond) {
        message(paste("URL caused a warning:", url))
        message("Here's the original warning message:")
        message(cond)
        # Choose a return value in case of warning
        return(NULL)
    },
    finally={
    # NOTE:
    # Here goes everything that should be executed at the end,
    # regardless of success or error.
    # If you want more than one expression to be executed, then you 
    # need to wrap them in curly brackets ({...}); otherwise you could
    # just have written 'finally=<expression>' 
        message(paste("Processed URL:", url))
        message("Some other message at the end")
    }
)    
return(out)
}

来源来自this stackoverflow响应,我显然建议您看一下。


0
投票

您需要一种捕获错误的方法。为此我很欣赏的一个工具是safely()包中的purrr

将您的函数包装在现有函数调用周围,即使发生错误,该函数也可以安全地返回输出。

从文档(log()示例::

safe_log <- safely(log)
safe_log(10)
#> $result
#> [1] 2.302585
#> 
#> $error
#> NULL
#> 
safe_log("a")
#> $result
#> NULL
#> 
#> $error
#> <simpleError in .Primitive("log")(x, base): non-numeric argument to mathematical function>
#> 

这将返回一个列表,其中包含结果和错误元素。


0
投票

使用try命令。

通常,这将导致错误并阻止随后运行的代码运行:

x <- "a" + 1
y <- 1
y

但是,如果我们在try中的赋值运算符之后包装零件,则会显示错误,但之后编写的代码仍然可以运行:

x <- try("a" + 1)
y <- 1
y

请注意,x具有类"try-error"

class(x)
"try-error"

因此,在您的示例中,您可以执行以下操作以确保以后的行能够运行,同时仍然能够拾取之前的行失败:

x <- try(sqlQuery(myConn,"exec sp_v_table_3"))
y <- 1
y
class(x) 

仍将创建对象y,并且x的类别将告诉您sqlQuery(myConn,"exec sp_v_table_3")是否成功运行。

tryCatch在某种意义上是try的一种更灵活的版本。 try仅在发生错误时返回类"try-error",并允许以后的代码行运行,但是tryCatch将允许您指定发生错误时要发生的情况。您也可以指定发生warning或代码成功运行时想要发生的情况。

© www.soinside.com 2019 - 2024. All rights reserved.