1

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.

victoria
  • 43
  • 1
  • 7
  • `library(dplyr); list %>% bind_rows(.id = "dataID")`, given that you have a named list. – Kim Mar 28 '19 at 21:31
  • Possible duplicate of [Convert a list of data frames into one data frame](https://stackoverflow.com/questions/2851327/convert-a-list-of-data-frames-into-one-data-frame) – Kim Mar 28 '19 at 21:31
  • @Kim I think you should re read the question, look at the required output – Hector Haffenden Mar 28 '19 at 21:37
  • Victoria, do you have an idea of the method you want to use? for loop, apply function etc.. And are you able to change the data, like in Cettt's answer. – Hector Haffenden Mar 28 '19 at 21:59
  • @HectorHaffenden I am not able to change the data. I have a list called listNAMES which equals to the names of the data frames contain in list – victoria Mar 28 '19 at 22:13

1 Answers1

1

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
Cettt
  • 11,460
  • 7
  • 35
  • 58