I would like to transform a list of data frames to one big data frame. The problem is, that I only have the list and not the separate data frames. An additional column with the names of data frames and without the rownames should be included in the new data frame.
Here's what I tried:
d1 <- data.frame(x = c(1.1,2.0,3.5), y = c(4.1,5.1,6.3))
d2 <- data.frame(x = c(3.3,2.7,1.9,2.9,1.9),y = c(6.4,5.2,2.4,3.0,5.1))
d3 <- data.frame(x = c(3.4,2.7,1.8,0.2),y = c(6.2,5.0,4.1,0.5))
my.list <- list(green = d1, blue = d2, yellow = d3)
The target data frame should look like this:
target.df <- data.frame(colour = c(rep("green",nrow(d1)), rep("blue", nrow(d2)), rep("yellow", nrow(d3))),
x = c(1.1,2.0,3.5, 3.3,2.7,1.9,2.9,1.9, 3.4,2.7,1.8,0.2),
y = c(4.1,5.1,6.3, 6.4,5.2,2.4,3.0,5.1, 6.2,5.0,4.1,0.5)
)
The code
my.df <- do.call(rbind.data.frame, my.list)
produces a dataframe with row names from the names of data frames instead of an extra column.
I tried this:
new.df <- stack(my.list)
But there is Error in stack.default(my.list) : at least one vector element is required
How can I produce the target data frame?