2016-12-27 49 views
0

我需要返回「try-error」類或繼承它的相同類。在R中可能嗎?如何在R中創建try-error類

那麼,是不是可以這樣創建功能:

Foo <- function(x) 
{ 
    if (x != 2) { res <- 1 } 
    else { res <- # create object with class type "try-error" and message "I hate 2!"/ } 

    return(res); 
} 

回答

4

類是R中一個非常鬆散的概念;你可以在對象的class屬性中指定你想要的任何類作爲字符串。例如,使用structure功能:

Foo <- function(x) { 
    if (x != 2) { 
     res <- 1 
    } else { 
     res <- structure(
      "message", 
      class = c("try-error", "character") 
     ) 
    } 
    res 
} 

Foo(1) 
# [1] 1 

Foo(2) 
# [1] "message" 
# attr(,"class") 
# [1] "try-error" "character" 

class(Foo(2)) 
# [1] "try-error" "character" 

另外,還可以代替structure使用

res <- "message" 
class(res) <- c("try-error", class(res)) 

它通常是一個好主意,添加新類,而不是完全覆蓋舊的類,這樣的方法分派工作得相當,但根據您的使用情況下,這可能並不需要或期望。


+0

謝謝!這就是我需要的! – Dmitriy

1

爲什麼不使用try

Foo <- function(x) 
{ res <- try({ 
    if (x == 2L) stop("I hate 2!", call. = FALSE) 
    1 
    }) 
    res 
} 

Foo(2) 
#Error : I hate 2! 
#[1] "Error : I hate 2!\n" 
#attr(,"class") 
#[1] "try-error" 
#attr(,"condition") 
#<simpleError: I hate 2!> 

我看不出你爲什麼要手動創建類「try-error」的對象的好理由。

+0

是的,這也是一個可以接受的解決方案! – Dmitriy

+0

手動創建對象的原因可以用下面的僞代碼來描述:A < - Foo(x);如果(A == 2){res < - 「我討厭2!」; class(res)< - c(「try-error」,class(res)); } else {res < - 100; } SendSomewhere(res); foo2的(3); – Dmitriy

+0

如果您需要錯誤處理,請使用R的設施進行錯誤處理。不要重新發明輪子。 – Roland