好吧:欢迎来到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 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)
}
应用代码
> 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
expr
除非有错误或警告,否则返回与执行相关的值。在这种情况下,return(NA)
可以通过提供相应的处理函数(请参阅参数error
和warning
中的?tryCatch
)来指定特定的返回值(请参见上文)。这些可以是已经存在的函数,但是您也可以在内部定义它们tryCatch()
(就像我上面所做的那样)。
选择处理程序函数的特定返回值的含义
如我们所指定的,NA
如果出现错误应返回,其中的第三个元素y
是NA
。如果我们选择NULL
将其作为返回值,则其长度y
将一直为,2
而不是3
那样,lapply()
而只是“忽略”返回值are NULL
。还要注意,如果您没有通过指定显式的返回值return()
,则处理程序函数将返回NULL
(即,在出现错误或警告条件的情况下)。
“不希望的”警告消息
由于warn=FALSE
似乎没有任何效果,另一种方式来抑制警告(在这种情况下是不是真的感兴趣)是使用
suppressWarnings(readLines(con=url))
代替
readLines(con=url, warn=FALSE)
多种表达
请注意,您也可以放置在“实际表达的一部分”多个表达式(参数expr
的tryCatch()
),如果你在大括号包起来(就像我在所示finally
部分)。
paste
函数中的第一个字符串以空格结尾,为什么不省略空格和sep=""
?