Search code examples
rlistdataframesapply

Custom Data Set/Frame From List


Sample

A=data.frame("id"=c(1:10))
B=data.frame("id"=c(7:16))
C=data.frame("id"=c(-10:-1))

mylist=c(A,B,C)

What I want is a list which combindes these three data.frames into a single one:

WANT = data.frame("id"=c(1:10,7:16,-10:-1),
                  dataID=c(rep("A",10),rep("B",10),rep("C",10)))

If suppose I have list which contains a bunch of data frames (this is how I am given the data). I want to put them into one really big data frame/set like "WANT" that uses the names of the data sets in the list for dataID. I am able to do this with just a few for example A,B,C but I have like a hundred and am wondering how do i pull out the data frames in list and make a tall file like the "WANT" example.


Solution

  • you can add the dataID into the single dataframes and then bind them together:

    EDIT: after some clarification, here is a new approach listNAMES = letters[1:3]

        library(tidyverse)
        tibble(mydata = list(A, B, C),
               dataID = listNAMES) %>% 
          unnest()
        # A tibble: 30 x 2
       names    id
       <chr> <int>
     1     1     1
     2     1     2
     3     1     3
     4     1     4
     5     1     5
     6     1     6
     7     1     7
     8     1     8
     9     1     9
    10     1    10
    # ... with 20 more rows