tryCatch() 関数の使い方は?質問する

tryCatch() 関数の使い方は?質問する

tryCatchWeb からデータをダウンロードする際のエラーに対処するために、を使用してコードを記述したいと思います。

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)

これら 2 つのステートメントは正常に実行されます。以下では、存在しない Web アドレスを作成します。

url <- c("xxxxx", "http://en.wikipedia.org/wiki/Xz")

url[1]存在しません。tryCatchループ (関数) をどのように記述すればよいでしょうか。

  1. URL が間違っている場合、出力は「Web URL が間違っているため、取得できません」となります。
  2. URL が間違っている場合、コードは停止せず、URL リストの最後までダウンロードを続行しますか?

ベストアンサー1

コードの設定

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) {
    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")

            suppressWarnings(readLines(url))
            # The return value of `readLines()` is the actual value
            # that will be returned in case there is no condition
            # (e.g. warning or error).
        },
        error = function(cond) {
            message(paste("URL does not seem to exist:", url))
            message("Here's the original error message:")
            message(conditionMessage(cond))
            # Choose a return value in case of error
            NA
        },
        warning = function(cond) {
            message(paste("URL caused a warning:", url))
            message("Here's the original warning message:")
            message(conditionMessage(cond))
            # Choose a return value in case of warning
            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")
        }
    )
}

コードの使用

> y <- lapply(urls, readUrl)
This is the 'try' part
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
This is the 'try' part
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
This is the 'try' part
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

出力の調査

> head(y[[1]])
[1] "<!DOCTYPE html><html><head><title>R: Functions to Manipulate Connections (Files, URLs, ...)</title>"
[2] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
[3] "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\" />"
[4] "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css\">"
[5] "<script type=\"text/javascript\">"
[6] "const macros = { \"\\\\R\": \"\\\\textsf{R}\", \"\\\\code\": \"\\\\texttt\"};"

> length(y)
[1] 3

> y[[3]]
[1] NA

追加コメント

tryCatch

tryCatchエラーまたは警告がない限り、実行に関連付けられた値を返しますexpr。この場合、特定の戻り値 (NA上記を参照) は、それぞれのハンドラー関数 (の引数errorwarningを参照?tryCatch) を提供することで指定できます。これらは既存の関数にすることもできますが、(上記のように) 内で定義することもできますtryCatch()

ハンドラ関数の特定の戻り値を選択することの意味

NAエラーの場合は が返されるように指定したので、 の 3 番目の要素yは ですNA

おすすめ記事