Reputation: 939
I need to return "try-error" class or same class which inherits from it. Is it possible in R?
So, is it possible to create function like this:
Foo <- function(x)
{
if (x != 2) { res <- 1 }
else { res <- # create object with class type "try-error" and message "I hate 2!"/ }
return(res);
}
Upvotes: 0
Views: 2247
Reputation: 132676
Why don't you use 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!>
I can't see a good reason why you'd create an object of class "try-error" manually.
Upvotes: 2
Reputation: 18602
Classes are a pretty loose concept in R; you can just assign any class(es) you desire as character strings in the class
attribute of an object. For example, using the structure
function:
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"
Alternatively, you could use
res <- "message"
class(res) <- c("try-error", class(res))
in place of structure
.
It's usually a good idea to add new classes rather than completely overwrite the old classes so that method dispatch works reasonably, but depending on your use case this may not be needed or desired.
Upvotes: 4