[r] R에 “warnings ()”가 나타날 때 루프 중단

문제가 있습니다. 여러 파일을 처리하기 위해 루프를 실행하고 있습니다. 내 행렬은 엄청 나기 때문에 조심하지 않으면 종종 메모리가 부족합니다.

경고가 생성 된 경우 루프에서 벗어날 수있는 방법이 있습니까? 루프를 계속 실행하고 훨씬 나중에 실패했다고보고합니다. 오 현명한 stackoverflow-ers 어떤 아이디어?!



답변

다음을 사용하여 경고를 오류로 전환 할 수 있습니다.

options(warn=2)

경고와 달리 오류는 루프를 중단합니다. 훌륭하게도 R은 이러한 특정 오류가 경고에서 변환되었음을보고합니다.

j <- function() {
    for (i in 1:3) {
        cat(i, "\n")
        as.numeric(c("1", "NA"))
}}

# warn = 0 (default) -- warnings as warnings!
j()
# 1 
# 2 
# 3 
# Warning messages:
# 1: NAs introduced by coercion 
# 2: NAs introduced by coercion 
# 3: NAs introduced by coercion 

# warn = 2 -- warnings as errors
options(warn=2)
j()
# 1 
# Error: (converted from warning) NAs introduced by coercion


답변

R을 사용하면 조건 처리기를 정의 할 수 있습니다.

x <- tryCatch({
    warning("oops")
}, warning=function(w) {
    ## do something about the warning, maybe return 'NA'
    message("handling warning: ", conditionMessage(w))
    NA
})

결과적으로

handling warning: oops
> x
[1] NA

tryCatch 후에 실행이 계속됩니다. 경고를 오류로 변환하여 종료하기로 결정할 수 있습니다.

x <- tryCatch({
    warning("oops")
}, warning=function(w) {
    stop("converted from warning: ", conditionMessage(w))
})

또는 조건을 적절하게 처리 (경고 호출 후 계속 평가)

withCallingHandlers({
    warning("oops")
    1
}, warning=function(w) {
    message("handled warning: ", conditionMessage(w))
    invokeRestart("muffleWarning")
})

어느 인쇄

handled warning: oops
[1] 1


답변

글로벌 warn옵션을 설정합니다 .

options(warn=1)  # print warnings as they occur
options(warn=2)  # treat warnings as errors

“경고”는 “오류”가 아닙니다. 루프는 경고로 종료되지 않습니다 (제외 options(warn=2)).


답변