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

Janko Thyson janko.thyson.rstuff at googlemail.com
Thu Jul 7 16:25:32 CEST 2011


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!



More information about the R-help mailing list