[R] Simple inheritance check fails (integer from numeric)

David Winsemius dwinsemius at comcast.net
Thu Jul 7 18:25:52 CEST 2011


On Jul 7, 2011, at 10:25 AM, Janko Thyson wrote:

> On 07.07.2011 16:09, David Winsemius wrote:
>>
>> On Jul 7, 2011, at 6:01 AM, Janko Thyson wrote:
>>
>>> Dear list,
>>>
>>> In a function, I don't care if my input has class 'integer' or  
>>> 'numeric', so I wanted to use 'inherits()' to control for that.
>>>
>>> However, this function tells me that an actual object of class  
>>> 'integer' does not inherit from class 'numeric'. The class def of  
>>> 'integer' does state 'numeric' as one of the superclasses. Isn't  
>>> that somewhat inconsistent?
>>>
>>> > getClass("integer")
>>> Class "integer" [package "methods"]
>>>
>>> No Slots, prototype of class "integer"
>>>
>>> Extends: "numeric", "vector", "data.frameRowLabels"
>>>
>>> > a <- 1:3
>>> > class(a)
>>> [1] "integer"
>>>
>>> > inherits(a, "numeric")
>>> [1] FALSE
>>>
>>
>> > a <- 1:3
>> > is.numeric(a)
>> [1] TRUE
> ;-) Sure, but for me that doesn't explain why 'inherits()' won't  
> recognize the inheritance. And it's not generic enough for the  
> methods I'd like to write.
>
> I'd like to check if, say, 'src' inherits from 'tgt' which would  
> specifies an arbitrary class. And I would like to get around testing  
> all sorts of combinations like "if  'tgt' specifies class 'numeric',  
> then try 'is.numeric(src)'":
>
> simpleFoo <- function(src, tgt){
>    if(inherits(src, tgt)){
>        print("yep")
>    } else {
>        print("nope")
>    }
> }
> x <- 1:3
> class(x) <- c(class(x), "AAA")
> simpleFoo(src=x, tgt="AAA")
>
> x <- 1:3
> simpleFoo(src=x, tgt="numeric")
>
> But thanks for the answer!

This is Prof. Ripley's advice from a rather long time ago, but I do  
notice that the strategy of checking for inherited classes is still  
used by others.

http://finzi.psych.upenn.edu/R/Rhelp02/archive/24704.html

If the goal is to avoid an error interrupting execution perhaps you  
could instead use try().


>
>
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list