- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想写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
循环(函数)以便:
最佳答案
那么:欢迎来到 R 世界 ;-)
给你
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 inside 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)
}
> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory
> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""
> length(y)
[1] 3
> y[[3]]
[1] NA
tryCatch
tryCatch
返回与执行 expr
相关的值,除非出现错误或警告。在这种情况下,可以通过提供相应的处理函数(参见参数 error
和 warning
来指定特定的返回值(参见上面的 return(NA)
) > 在 ?tryCatch
中)。这些可以是已经存在的函数,但您也可以在 tryCatch()
中定义它们(就像我在上面所做的那样)。
选择处理函数的特定返回值的含义
正如我们指定的那样,NA
应该在出错的情况下返回,y
中的第三个元素是 NA
。如果我们选择 NULL
作为返回值,则 y
的长度将只是 2
而不是 3
as lapply()
将简单地“忽略”NULL
的返回值。另请注意,如果您未通过 return()
指定 explicit 返回值,则处理函数将返回 NULL
(即,如果错误或警告条件)。
“不受欢迎的”警告消息
由于 warn=FALSE
似乎没有任何效果,另一种抑制警告的方法(在这种情况下并不是真正感兴趣的)是使用
suppressWarnings(readLines(con=url))
代替
readLines(con=url, warn=FALSE)
多重表达
请注意,如果将多个表达式用大括号括起来(就像我在 finally
部分进行了说明)。
关于r - 如何在 R 中编写 trycatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33733102/
考虑以下代码: test1 print(test1) [1] "b" > print(test2) [1] "b" 最佳答案 '<<-' 是为不属于 R 的副作用而设计的。永远不要使用它,或者只有在
我正在编写一个函数,该函数使用 kmeans 来确定 bin 宽度,以将连续测量值(预测概率)转换为整数(3 个 bin 之一)。我偶然发现了一个边缘情况,在这种情况下,我的算法可以(正确)预测整个集
我注意到 tryCatch 没有正确捕获以下错误:它不打印 TRUE,并且它不转到浏览器... 它可能是 tryCatch 函数中的错误吗? library(formattable) df1 = st
我对 R 很陌生,我对 tryCatch 的正确用法感到困惑.我的目标是对大型数据集进行预测。如果预测不适合内存,我想通过拆分我的数据来规避这个问题。 现在,我的代码大致如下: tryCatch({
myFunc <- function(x) { x <- timeSeries(x, charvec=as.Date(index(x))) t<-tryCatch( doSomething(
我尝试连接 2 个数据框:Eset2 和 Essential。它们共享 1 个包含基因名称的公共(public)列,并且两个框架都有唯一的行。 所以我决定在 Eset2 中查找我需要的值(RMA,AN
我想知道这是检查 tryCatch 函数类型的错误或警告的方法,例如在 Java 中。 try { driver.findElement(By.xpath(locator)).
我正在尝试使用 tryCatch 生成 p 值列表,矩阵中有几行没有足够的观察值来进行 t 检验。这是我到目前为止生成的代码: pValues <- c() for(i in row.names(co
我有一个 1000 行的数据框。我想要循环的代码非常简单 - 我只想将第 4 列中的所有值设为大写。我希望它能够在任何行中出现错误时跳过该行并继续执行其余行。 我写了这段代码: for(i in 1:
我有一段代码,其中使用 for 循环读取和分析文件列表。由于我必须分析多个文件,因此我想使用 tryCatch 来打印引发问题的文件的名称。我的文件的一个常见问题是缺少列名,我的意思是,它应该在文件中
这将输出“未发现错误!”两次, x .8) stop("oops") TRUE } g = function() { ## on error, warn user but contin
我正在解析大量网站并编写了一个脚本,该脚本循环遍历来自单独文件的数千个链接。但是,我遇到过有时 R 无法加载一个链接,它会在循环中间停止,从而导致许多其他 url 无法解析。所以我尝试使用 tryCa
我有一个 1000 行的数据框。我想要循环的代码非常简单 - 我只想将第 4 列中的所有值设为大写。我希望它能够在任何行中出现错误时跳过该行并继续执行其余行。 我写了这段代码: for(i in 1:
我正在使用 tryCatch捕捉发生的任何错误。但是,即使我捕获它们并返回适当的错误值,看起来我的批处理系统的日志中仍然报告错误。有没有办法完全抑制错误并简单地继续我提供的错误处理? 最佳答案 确保您
我有一段代码,其中使用 for 循环读取和分析文件列表。由于我必须分析多个文件,因此我想使用 tryCatch 来打印引发问题的文件的名称。我的文件的一个常见问题是缺少列名,我的意思是,它应该在文件中
import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class Images { t
下面的tryCatch装饰器无法捕捉到错误。 const TryCatchWrapper = (target, key, descriptor) => { const fn = descripto
我在排列数据上运行 GLMM,对于其中一些我有收敛的错误消息。 由于这是我的空模型,我只需要重新采样这个特定的排列数据。 因此,我试图处理 R 的 tryCatch 函数,但我有一些失败。 我有 Pe
我试图在 for 循环中处理两个可能的错误,它调用 stplanr::dist_google与 API 交互。我知道错误,所以我想在它们发生时采取具体的行动。 如果我尝试仅处理可能的错误之一,它会起作
我有一个函数: buggy buggy() Error in tryCatchList(expr, classes, parentenv, handlers) : I don't like gr
我是一名优秀的程序员,十分优秀!