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.
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 …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With