How to know if the data is a list or data.frame in R
Asked Answered
A

2

29

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?

Armallas answered 23/7, 2016 at 8:13 Comment(1)
data.frame is a special kind of list. Read this and this.Boatman
B
39

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.

Benson answered 23/7, 2016 at 8:24 Comment(0)
T
0

obj_is_list() can help you determine if your object is a list (not necessarily if it is a data frame though):

library(vctrs)

obj_is_list(data.frame())
# [1] FALSE

obj_is_list(list())
# [1] TRUE
Teletypesetter answered 24/7, 2024 at 22:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.