24

How do I know if my data in R is a list or a data.frame?

If I use typeof(x) it says list, if I use class(x) it says data.frame?

Jaap
  • 81,064
  • 34
  • 182
  • 193
carlosmaria
  • 277
  • 1
  • 2
  • 7
  • 1
    `data.frame` is a special kind of `list`. Read [this](http://stackoverflow.com/questions/6258004/r-types-and-classes-of-variables) and [this](http://stackoverflow.com/documentation/r/438/data-frames/1458/create-an-empty-data-frame#t=201607230816043614997). – Sumedh Jul 23 '16 at 08:19

1 Answers1

35

To clarify a possible misunderstanding given the title of your question, a data.frame is also a list.

is.list(data.frame())   # TRUE

However, you can use inherits() to see if an object is a list or data.frame

inherits(data.frame(), "data.frame")  # TRUE
inherits(list(), "data.frame")        # FALSE
    
inherits(data.frame(), "list")        # FALSE
inherits(list(), "list")              # TRUE

Or alternatively, methods::is(), but is ever-so-slightly slower.

is(data.frame(), "data.frame")  # TRUE
is(list(), "data.frame")        # FALSE

is(data.frame(), "list")        # FALSE
is(list(), "list")              # TRUE

From ?is help page:

Although inherits is defined for S3 classes, it has been modified so that the result returned is nearly always equivalent to is, both for S4 and non-S4 objects. Since it is implemented in C, it is somewhat faster.

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139