What is the preferred method of checking an object's class in R?
(1)
is.data.frame(df)
(2)
class(df) == 'data.frame'
(3)
'data.frame' %in% class(df)
What is the correct way to determine class in R? class(newVar) gives list .
To determine the class of any R object's “internal” type, use the class() function. If the object does not have a class attribute, it has an implicit class, prominently “matrix“, “array“, “function” or “numeric,” or the result of typeof(x). The class() function is robust.
To get type of a value or variable or object in R programming, call typeof() function and pass the value/variable to it.
A class is just a blueprint or a sketch of these objects. It represents the set of properties or methods that are common to all objects of one type. Unlike most other programming languages, R has a three-class system. These are S3, S4, and Reference Classes.
I would say
inherits(df,"data.frame")
or
is(df,"data.frame")
among other things, #2 in your list can fail because (as you suggest in #3) class(df)
can have length > 1. (is.data.frame
is nice, but not all classes have is.
methods: see methods("is")
)
For me it'd be:
is.data.frame(df)
Is a clearer option to use in conditions. Also, is the 'less code' option of the three, if that is important for you.
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