Что ж: добро пожаловать в мир 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
, если нет ошибки или предупреждения. В этом случае конкретные возвращаемые значения (см. return(NA)
выше) могут быть указаны путем предоставления соответствующей функции-обработчика (см. Аргументы error
и warning
в ?tryCatch
). Это могут быть уже существующие функции, но вы также можете определить их в tryCatch()
(как я сделал выше).
Последствия выбора конкретных возвращаемых значений функций-обработчиков
Как мы указали, что NA
должен быть возвращен в случае ошибки, третий элемент в y
- это NA
. Если бы мы выбрали NULL
в качестве возвращаемого значения, длина y
была бы просто 2
вместо 3
, поскольку lapply()
просто игнорирует возвращаемые значения, которые равны NULL
. Также обратите внимание, что если вы не укажете явное возвращаемое значение через return()
, функции-обработчики вернут NULL
(т. Е. В случае ошибки или условия предупреждения).
Нежелательное предупреждающее сообщение
Поскольку warn=FALSE
, похоже, не имеет никакого эффекта, альтернативным способом подавления предупреждения (которое в данном случае не представляет особого интереса) является использование
suppressWarnings(readLines(con=url))
вместо того
readLines(con=url, warn=FALSE)
Несколько выражений
Обратите внимание, что вы также можете поместить несколько выражений в фактическую часть выражений (аргумент expr
из tryCatch()
), если заключите их в фигурные скобки (как я проиллюстрировал в части finally
).
person
Community
schedule
30.08.2012