452

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)

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

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

url[1]存在しません。trycatch次のようにループ(関数) をどのように記述しますか。

  1. URL が間違っている場合、出力は次のようになります: "web URL is wrong, can't get".
  2. URL が間違っている場合、コードは停止せず、URL のリストの最後までダウンロードし続けますか?
4

5 に答える 5

819

それでは、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

補足事項

トライキャッチ

tryCatchexprエラーまたは警告がない限り、実行に関連付けられた値を返します。この場合、特定の戻り値 (return(NA)上記を参照) は、それぞれのハンドラ関数を指定することによって指定できます (引数errorおよびwarningを参照?tryCatch)。これらは既に存在する関数である可能性がありますが、内部で定義することもできますtryCatch()(上記で行ったように)。

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

NAエラーの場合に が返されるように指定したように、 の 3 番目の要素はyですNA。戻り値として選択NULLした場合、 の長さは、 の戻り値を単純に「無視」するのでy2なく、3になります。また、 を介して明示的な戻り値を指定しない場合、ハンドラー関数は戻ります(つまり、エラーまたは警告状態の場合)。lapply()NULLreturn()NULL

「望ましくない」警告メッセージ

warn=FALSE効果がないように見えるため、警告を抑制する別の方法 (この場合はあまり重要ではありません) を使用することです。

suppressWarnings(readLines(con=url))

それ以外の

readLines(con=url, warn=FALSE)

複数の式

中括弧で囲むと、「実際の式の部分」(exprの引数)に複数の式を配置することもできることに注意してください(その部分で説明したように)。tryCatch()finally

于 2012-08-30T11:12:08.157 に答える
81

R は try-catch ブロックを実装するために関数を使用します。

構文は次のようになります。

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

tryCatch() には、「警告」と「エラー」という 2 つの「条件」を処理できます。コードの各ブロックを記述する際に理解しておくべき重要なことは、実行の状態とスコープです。 @ソース

于 2012-08-30T09:34:14.163 に答える
52

簡単な例を次に示します。

# Do something, or tell me why it failed
my_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=部分を追加するだけです。

于 2017-04-13T00:25:10.817 に答える
31

Irr 関数の tryCatch を解こうとして人生の 2 日間を失ったばかりなので、私の知恵 (および不足しているもの) を共有する必要があると考えました。参考までに-irrは、この場合、大規模なデータセットでいくつかのケースでエラーが発生したFinCalの実際の関数です。

  1. 関数の一部として tryCatch を設定します。例えば:

    irr2 <- function (x) {
      out <- tryCatch(irr(x), error = function(e) NULL)
      return(out)
    }
    
  2. エラー (または警告) が機能するには、実際に関数を作成する必要があります。私はもともとエラー部分のために書いたばかりerror = return(NULL)で、すべての値がnullに戻ってきました。

  3. サブ出力 (私の「出力」など) と to を作成することを忘れないでくださいreturn(out)

于 2016-09-25T18:55:30.203 に答える