What's the difference between is and inherits? What's the difference between is and inherits? r r

What's the difference between is and inherits?


Short version:

Use inherits, but be careful with numbers and S4 classes.


Longer version:

From the See Also section of the is help page:

inherits is nearly always equivalent to is, both for S4 and non-S4 objects, and is somewhat faster. The non-equivalence applies to classes that have conditional superclasses, with a non-trivial test= in the relation (not common and discouraged): for these, is tests for the relation but inherits by definition ignores conditional inheritance for S4 objects.

From the Formal Classes section of the inherits help page:

The analogue of inherits for formal classes is is. The two functions behave consistently with one exception: S4 classes can have conditional inheritance, with an explicit test. In this case, is will test the condition, but inherits ignores all conditional superclasses.

So they mostly return the same thing, but inherits is faster, so it should be the default choice in most cases. (As mentioned by Konrad, is also requires that the methods package is loaded, which may make it unsuitable for performance sensitive uses of Rscript.)

The values can differ if you are using S4 classes with conditional inheritance, but this is not recommended (see "Method Selection and Dispatch: Details" section), which means that it is hopefully rare.

The most obvious place where the two functions differ is when checking if integers are numeric.

class(1L)## [1] "integer"is.numeric(1L)## [1] TRUEis(1L, "numeric")## [1] TRUEinherits(1L, "numeric")## [1] FALSE