0

I have a list of dataframes and the name of each list has information that needs to be carried through to a column (I am going to bind all the dataframes). Is there a way to take this list name and make it a label in a column?

If the list starts out looking like this with head(my_list)

$day0005
# A tibble: 24 x 4
TSOIL1   lon   lat  TIME
<dbl> <dbl> <dbl> <dbl>
 1    265 -95.8  45.7   0  
 2    265 -95.8  45.7  60.0
 3    265 -95.8  45.7 120  
 4    265 -95.8  45.7 180  
 5    265 -95.8  45.7 240  

I would like each to look like

$day0005
# A tibble: 24 x 4
TSOIL1   lon   lat  TIME     day
<dbl> <dbl> <dbl> <dbl>     day0005
 1    265 -95.8  45.7   0   day0005
 2    265 -95.8  45.7  60.0 day0005
 3    265 -95.8  45.7 120   day0005
 4    265 -95.8  45.7 180   day0005
 5    265 -95.8  45.7 240   day0005

If your data started in a list and, as a result, you are including "list" in your search terms, congratulations, you have come to the right question. The answer here is simple and awesome.

If you started out with a bunch of dataframes, you may also want to look at the question that is similar to this one. They will show you how to turn your bunch of dataframes into a list of dataframes. Then come back here for the simplest answer related to identifying and binding ALL the rows.

Nazer
  • 3,654
  • 8
  • 33
  • 47
  • 3
    Please give a small example and the results you expect – Onyambu Feb 05 '18 at 22:40
  • 1
    Very similar to https://stackoverflow.com/questions/15162197/combine-rbind-data-frames-and-create-column-with-name-of-original-data-frames and its many linked questions. – thelatemail Feb 05 '18 at 22:53
  • Thanks, but the answer here is much easier. And I am starting out with a list (which is why I didn't turn up those non-list questions). – Nazer Feb 05 '18 at 23:00

2 Answers2

1

You can do this using dplyr::bind_rows():

library(dplyr)
mylist <- list(x = data.frame(a = 1:10), 
               y = data.frame(a = 11:20))

mydf <- mylist %>% 
  bind_rows(.id = "dfname")

mydf

   dfname  a
1       x  1
2       x  2
3       x  3
4       x  4
5       x  5
6       x  6
7       x  7
8       x  8
9       x  9
10      x 10
11      y 11
12      y 12
13      y 13
14      y 14
15      y 15
16      y 16
17      y 17
18      y 18
19      y 19
20      y 20
neilfws
  • 32,751
  • 5
  • 50
  • 63
0

Try this:

dl <-list(data.frame(a=1:10,b=11:20,c=20:11),data.frame(a=1:10,b=11:20,c=20:11),data.frame(a=1:10,b=11:20,c=20:11),data.frame(a=1:10,b=11:20,c=20:11))
names(dl) <- c("one","two","three","four")
dl <- Map(cbind,dl,"names" = names(dl))
Brian Davis
  • 990
  • 5
  • 11