Any reasons to prefer is.character over class (object) == "character"?

I have a very simple question with R, do I have any reason to prefer using

is.character(object) 

than

  class(object) == "character" 

in R.

or other is.class functions.

+7
r
source share
1 answer

Besides the obvious arguments for readability and performance, you should almost never have to test a class of objects with class(foo) == "class" , since you cannot rely on it to give the correct result.

As nrussell commented, an S3 class system supports "inheritance" through tagging objects with more than one class name. As soon as more than one class name appears, this equality check will give nonsense.

Instead, use either:

 if (inherits(obj, 'class')) โ€ฆ action โ€ฆ 

Or, if you explicitly want to run an exact test, rather than an inheritance test (which should be extremely rare):

 if (identical(class(obj), 'class')) โ€ฆ action โ€ฆ 
+7
source share

All Articles