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?
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?
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.
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
© 2022 - 2025 — McMap. All rights reserved.
data.frame
is a special kind oflist
. Read this and this. – Boatman