R에서 트라이캐치를 쓰는 방법
는 나는쓰싶다니습고를 쓰고 싶습니다.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루프(함수)를 사용하여 다음을 수행합니다.
- URL이 잘못된 경우 출력은 "웹 URL이 잘못됨, 가져올 수 없음"이 됩니다.
- URL이 틀리면 코드가 멈추지 않고 URL 목록이 끝날 때까지 다운로드를 계속합니까?
그렇다면: 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 관련값반다니환합을된행다를 실행하는 것과 합니다.expr오류나 경고가 없는 한.)return(NA)각 함수 위 참조)를할 수 있습니다.error그리고.warning?tryCatch). , 안에서 할 수도 tryCatch()(위에서 한 것처럼).
핸들러 함수의 특정 반환 값 선택의 의미
.NA에는 류가발경반의 세 인 오번요소는세째다합니야해생환우할▁in▁in▁returned,▁element▁the▁should▁be▁third는요소▁case▁of▁error세째번을 반환해야 합니다.y이라NA가 가선라면더했택리우면을 선택했다면.NULL될 , 환반 ,y그랬더라면2에 3~하듯이lapply()단순히 다음과 같은 값을 반환합니다.NULL또한 명시적인 반환 값을 지정하지 않은 경우 다음을 통해return()는 " " " 를 반환합니다.NULL(즉, 오류 또는 경고 조건의 경우).
원하지 않는 경고 메시지
~하듯이warn=FALSE아무런 영향을 미치지 않는 것으로 보이며, 경고를 억제하는 대안적인 방법(이 경우에는 실제로 관심이 없는 것)은 사용하는 것입니다.
suppressWarnings(readLines(con=url))
대신에
readLines(con=url, warn=FALSE)
다중 표현식
실제 표현식 부분에 여러 개의 표현식을 배치할 수도 있습니다(인수exprtryCatch()finally
tryCatch에는 약간 복잡한 구문 구조가 있습니다.그러나 아래와 같이 완전한 tryCatch 호출을 구성하는 4가지 부분을 이해하면 다음 사항을 쉽게 기억할 수 있습니다.
expr: [필수] 평가할 R 코드
error : [Optional] expr에서 코드를 평가하는 동안 오류가 발생한 경우 실행할 항목
warning : [선택사항] expr에서 코드를 평가하는 동안 경고가 발생한 경우 실행할 작업
finally : [Optional] expr이 성공적으로 실행되었는지, 오류가 발생했는지, 경고가 발생했는지 여부에 관계없이 tryCatch 호출을 종료하기 직전에 실행할 대상
tryCatch(
expr = {
# Your code...
# goes here...
# ...
},
error = function(e){
# (Optional)
# Do this if an error is caught...
},
warning = function(w){
# (Optional)
# Do this if an warning is caught...
},
finally = {
# (Optional)
# Do this at the end before quitting the tryCatch structure...
}
)
따라서 값의 로그를 계산하는 장난감 예제는 다음과 같습니다.
log_calculator <- function(x){
tryCatch(
expr = {
message(log(x))
message("Successfully executed the log(x) call.")
},
error = function(e){
message('Caught an error!')
print(e)
},
warning = function(w){
message('Caught an warning!')
print(w)
},
finally = {
message('All done, quitting.')
}
)
}
이제 세 가지 사례를 실행합니다.
타당한 사례.
log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.
"경고" 사례
log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.
"오류" 사례
log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.
저는 제가 정기적으로 사용하는 유용한 사용 사례에 대해 썼습니다.자세한 내용은 여기에서 확인하십시오. https://rsangole.netlify.com/post/try-catch/
이것이 도움이 되기를 바랍니다.
R은 Try-Catch 블록을 구현하는 기능을 사용합니다.
구문은 다음과 같습니다.
result = tryCatch({
expr
}, warning = function(warning_condition) {
warning-handler-code
}, error = function(error_condition) {
error-handler-code
}, finally={
cleanup-code
})
TryCatch()에는 '경고'와 '오류'라는 두 가지 '조건'이 있습니다.각 코드 블록을 작성할 때 이해해야 할 중요한 것은 실행 상태와 범위입니다.@출처
다음은 간단한 예입니다.
# 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=
제 인생의 이틀을 부적절한 기능 때문에 tryCatch를 위해 해결하려다 잃었기 때문에, 저는 제 지혜(그리고 빠진 것)를 공유해야 한다고 생각했습니다.FYI - irr는 이 경우 FinCal의 실제 함수로, 큰 데이터 세트에서 몇 가지 경우에 오류가 발생했습니다.
함수의 일부로 tryCatch를 설정합니다.예:
irr2 <- function (x) { out <- tryCatch(irr(x), error = function(e) NULL) return(out) }오류(또는 경고)가 작동하려면 실제로 함수를 만들어야 합니다.는 원래 저는래원방금쓴오부대분다해니입서에류▁wrote다▁just▁part▁i니대▁origin라고 썼습니다.
error = return(NULL)모든 값이 null로 반환되었습니다.(과 같은) 하위 과 to를 하세요.
return(out).
그purrr는 패지는설더에편기대제기다체니공합능을리한키정보다 하기 쉬운 합니다.tryCatch?safely설명서는 다음과 같이 설명됩니다.
safely는 대신 래된함수대다반환니합다을음신는핑▁wrapped를 반환합니다.list요소 포함result그리고.error발생한 에는,error입니다.error와 적어와result이 있습니다.otherwise) 는 )입니다 그렇지 않으면 오류는NULL.quietly는 대신 래된함수대다반환니합다을음신는핑▁wrapped를 반환합니다.list요소 포함result,output,messages그리고.warnings.possibly합니다.otherwise) 발생할 오류가 발생할 때마다 표시됩니다.
은 한기다달음리과와는 사용된다는 하시기 바랍니다.tryCatch()식이 아닌 함수를 래핑해야 하며 수정된 함수를 반환합니다.언급된 OP의 문제에 대해서는, 우리는possibly 그고랩 리고랩.readLines직접 수정할 수 있습니다.
url <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",
"xxx")
library(purrr)
lapply(url, possibly(readLines, otherwise = "web URL is wrong, can't get"))
## with possibly, the error prints as a warning
## and the final value is the `otherwise` string
하지만 다음의 수정된 버전을 만들 수도 있습니다.readLines를 들어, 를들어예와 같은my_readLines <- possibly(readLines, otherwise = "web URL is wrong, can't get")우리 코드의 여러 장소에서 사용될 수 있습니다.
저는 설니다합명으로 합니다.possibly위에서, 하지만 우리는 우리가 사용하고 싶은 경우를 쉽게 상상할 수 있습니다.safely()(그는 (그후우추수있다니었습출할는리에▁the다그니)를 추출할 수 result항목의 요소. 않은 할 수 . 각 목 항 록 의 거 나 건 뛰 비 있 너 않 항 은 을 목 할 있 음 수 리 처 지 을 항 목error 아마도도 있음) 구요소오류, 성도에따라다르처게리수또할도있는)quietly또한 경고와 메시지를 별도로 캡처합니다.
언급URL : https://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r
'source' 카테고리의 다른 글
| 설치된 Angular-cli 버전을 확인하는 중입니까? (0) | 2023.06.06 |
|---|---|
| 제한을 사용하여 dsl 삭제 쿼리를 쿼리했습니다. (0) | 2023.06.06 |
| 트리거 if-delete-clause를 생성할 수 없습니다. (0) | 2023.06.06 |
| 표에 댓글을 달려면 어떻게 해야 하나요 - 마리아DB (0) | 2023.06.06 |
| 오류 1366: 마리아에 문자열을 삽입할 때 잘못된 문자열 값DB (0) | 2023.06.06 |