Question

I'm a newbie here. I am trying to use S4 classes. In some of my setting methods, I would like to take an input value and test if it is valid. If it is valid, I would like to assign it. If it is not valid, I would like to generate a warning that can be tested for. Here is a simple example:

 setClass("foo", representation(ind = "numeric"))

 setGeneric(name="setInd<-",def=function(object,value){standardGeneric("setInd<-")})

 setReplaceMethod(f="setInd",signature="foo",
 def=function(object,value){
   if(is.numeric(value)){
     object@ind<-value;}
   else{
     warning("Foobar")
   }
    return(object)}
 )

This generates a warning message when I try to assign a character:

> thisFoo<-new("foo", ind = 2)
> thisFoo
An object of class "foo"
Slot "ind":
[1] 2


> setInd(thisFoo)<-"A"
Warning message:
In `setInd<-`(`*tmp*`, value = "A") : Foobar
> thisFoo
An object of class "foo"
Slot "ind":
[1] 2

But I would like to be able to test that the assignment failed. What is a good way of doing this? Thanks.

Was it helpful?

Solution

If the assignment fails, I'd return an error instead of a warning. A warning tells you that the process went through, but might give an unexpected result. In your case, the process is aborted :

setReplaceMethod(f="setInd",signature="foo",
 def=function(object,value){
   if(!is.numeric(value))
     stop("Foobar")

   object@ind <- value  
   return(object)}
 )

using stop allows you to use tryCatch() or try() constructs. See the relevant help pages for more information. Eg :

tryCatch(setInd(thisFoo)<-"A",error=function(e){print("Hello")})

> X <- try(setInd(thisFoo) <- "A")
Error in `setInd<-`(`*tmp*`, value = "A") : Foobar
> if(is(X,"try-error")) setInd(thisFoo) <- 5
> thisFoo
An object of class "foo"
Slot "ind":
[1] 5

If you really need to work with warnings, look at withCallingHandlers. Using your original code :

> withCallingHandlers({setInd(thisFoo)<-"A"},
+     warning = function(w) {print("Hello")})
[1] "Hello"
Warning message:
In `setInd<-`(`*tmp*`, value = "A") : Foobar

Mind you, this is less straightforward to use than the abovementioned options using errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top