[R] Converting a list to a data frame

Tóth Dénes toth@dene@ @end|ng |rom kogentum@hu
Thu May 3 09:33:08 CEST 2018

On 05/03/2018 07:58 AM, Jeff Newmiller wrote:
> This is very nice to learn about, Denis, but it seems only fair to point out that the result of rbindlist is not a data frame.  You can convert it to a data frame easily, but the copy and indexing semantics of data tables are quite different than data tables, which could be a real headache for someone not prepared for those differences. (To learn more, read the data tables vignette.)
> Tibbles  (as produced by unnest in my previous response) are not data tables either, but they behave much more like data frames than data tables do.
> On May 2, 2018 1:30:37 PM MDT, "Tóth Dénes" <toth.denes using kogentum.hu> wrote:
>> On 05/02/2018 07:11 PM, Kevin E. Thorpe wrote:
>>> I suspect this is pretty easy, but I'm having trouble figuring it
>> out.
>>> Basically, I have a list of data frames such as the following
>> example:
>>> list(A=data.frame(x=1:2, y=3:4),B=data.frame(x=5:6,y=7:8))
>>> I would like to turn this into  data frame where the list elements
>> are
>>> essentially rbind'ed together and the element name becomes a new
>>> variable. For example, I would like to turn the list above into a
>> data
>>> frame that looks like this:
>>> data.frame(type=c("A","A","B","B"),x=c(1:2,5:6),y=c(3:4,7:8))
>>> Appreciate any pointers.
>> Hi Kevin,
>> data.table::rbindlist does exactly what you want in a very efficient
>> way:
>> library(data.table)
>> dat <- list(A=data.frame(x=1:2, y=3:4),B=data.frame(x=5:6,y=7:8))
>> rbindlist(dat, idcol = "type")

In response to Jeff's note, this a solution which results in a 
data.frame instead of a data.table:

dat <- list(A=data.frame(x=1:2, y=3:4),B=data.frame(x=5:6,y=7:8))
dat <- rbindlist(dat, idcol = "type")

# traditional way
dat_df <- as.data.frame(dat)

# no copy (assignment not needed, memory-efficient)

Further amendments would be needed to transform the 'type' variable to a 
factor, if it is required.

>> Regards,
>> Denes
>>> Kevin
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list