There are many posts on converting list of data frames to single data frame (ex. here). However, I need to do that while preserving information from which list resulting rows are, i.e. I need to preserve an index of original list. If the list is unnamed, I need just an index number, while if the list is named I need to save the name of original list element. How can I do that?
With the data like below:
foo <- list(data.frame(x=c('a', 'b', 'c'),y = c(1,2,3)),
data.frame(x=c('d', 'e', 'f'),y = c(4,5,6)))
I need an output like this:
index x y
1 1 a 1
2 1 b 2
3 1 c 3
4 2 d 4
5 2 e 5
6 2 f 6
while with named elements of a list:
foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(1,2,3)),
df2 = data.frame(x=c('d', 'e', 'f'),y = c(4,5,6)))
the output would be:
index x y
1 df1 a 1
2 df1 b 2
3 df1 c 3
4 df2 d 4
5 df2 e 5
6 df2 f 6