Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred method of checking object's class in R

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) 
like image 429
pjvandehaar Avatar asked Jul 18 '13 20:07

pjvandehaar


People also ask

Which method is used to determine class of an R object?

What is the correct way to determine class in R? class(newVar) gives list .

How do I check classes in R?

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.

How do I identify an object in R?

To get type of a value or variable or object in R programming, call typeof() function and pass the value/variable to it.

What are the object classes in R?

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.


2 Answers

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"))

like image 123
Ben Bolker Avatar answered Sep 20 '22 17:09

Ben Bolker


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.

like image 31
mikyatope Avatar answered Sep 21 '22 17:09

mikyatope