为了账号安全,请及时绑定邮箱和手机立即绑定

如何在R中编写尝试捕获

如何在R中编写尝试捕获

UYOU 2019-06-18 13:45:25
如何在R中编写尝试捕获我想写trycatch处理从网上下载错误的代码。url <- c(     "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",     "http://en.wikipedia.org/wiki/Xz")y <- mapply(readLines, con=url)这两个语句成功运行。下面,我创建一个不存在的网址:url <- c("xxxxx", "http://en.wikipedia.org/wiki/Xz")url[1]不存在。如何编写trycatch循环(功能)以便:当URL错误时,输出将是:“web URL是错误的,无法获取”。当URL错误时,代码不会停止,而是继续下载到URL列表的末尾?
查看完整描述

3 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

r使用函数来实现try-catch块:

语法看起来有点像这样:

result = tryCatch({
    expr}, warning = function(warning_condition) {
    warning-handler-code}, error = function(error_condition) {
    error-handler-code}, finally={
    cleanup-code})

在try Catch()中,可以处理两个“条件”:“警告”和“错误”。在编写每个代码块时要理解的重要事情是执行状态和范围。@来源


查看完整回答
反对 回复 2019-06-18
?
慕的地6264312

TA贡献1817条经验 获得超6个赞

来了一个简单的例子:

# Do something, or tell me why it failedmy_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )}

如果您还想捕获“警告”,只需添加warning=类似于error=部分。


查看完整回答
反对 回复 2019-06-18
  • 3 回答
  • 0 关注
  • 544 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信