Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to prefer is.character than class(object) == "character"?

Tags:

r

I have a very simple question with R, is there any reason for me to prefer the usage of

 is.character(object) 

than

 class(object) == "character" 

in R.

or the other is.class functions.

like image 993
sinalpha Avatar asked Mar 14 '16 17:03

sinalpha


1 Answers

Besides the obvious readability and performance arguments, you should almost never test an object’s class via class(foo) == "class", as you cannot rely on it giving the correct result.

As nrussell commented, the S3 class system supports “inheritance” via tagging objects with more than one class name. As soon as more than a single class name is present, this equality check will yield nonsense.

Instead, use either:

if (inherits(obj, 'class'))
    … action …

Or, if you explicitly want to perform an exact test, not an inheritance test (which should be exceedingly rare):

if (identical(class(obj), 'class'))
    … action …
like image 86
Konrad Rudolph Avatar answered Nov 14 '22 18:11

Konrad Rudolph