Why does the class (data.frame (...)) not show list inheritance?

He often said that data.frame inherits from list , which makes sense, given the many common paradigms for accessing data.frame columns ( $ , sapply , etc.).

However, "list" does not apply to elements returned to the list of classes of the data.frame object:

 dat <- data.frame(x=runif(100),y=runif(100),z=runif(100),g=as.factor(rep(letters[1:10],10))) > class(dat) [1] "data.frame" 

The markup of a data.frame shows that this is a list:

 > class(unclass(dat)) [1] "list" 

And testing it seems that the default method will be called in preference to the list method if there is no data.frame method:

 > f <- function(x) UseMethod('f') > f.default <- function(x) cat("Default") > f.list <- function(x) cat('List') > f(dat) Default > f.data.frame <- function(x) cat('DF') > f(dat) DF 

Two questions:

  • Does refusal from data.frame formally inherit from list any design advantages?
  • How do these functions that appear to relate to data.frame are known to relate to them like lists? From looking at lapply it looks like it is quickly moving to the internal C code, so maybe this is so, but my mind is a little blown here.
+8
r r-s3
source share
1 answer

I admit that classes in R are a bit confusing to me. But I remember once reading something like "In R data.frames are actually lists of vectors." Using the code from your example, we can verify this:

 > is.list(dat) [1] TRUE ?is.list 

Note that we can also use the [[]] operator to access the elements (columns) of dat , which is the usual way to access list items in R:

 > identical(dat$x, dat[[1]]) [1] TRUE 

We can also verify that each column is actually a vector:

 > is.vector(dat$x) [1] TRUE 
+1
source share

All Articles