Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I have code that at one place ends up with a list of data frames which I really want to convert to a single big data frame.

I got some pointers from an earlier question which was trying to do something similar but more complex.

Here's an example of what I am starting with (this is grossly simplified for illustration):

listOfDataFrames <- vector(mode = "list", length = 100)

for (i in 1:100) {

    listOfDataFrames[[i]] <- data.frame(a=sample(letters, 500, rep=T),

                             b=rnorm(500), c=rnorm(500))

}

I am currently using this:

df <- do.call("rbind", listOfDataFrames)

1 Answer

0 votes
by

To combine several data frames into one data frame, you can use the bind_rows() function from the dplyr package that adds the unique row names based on the names of list elements.

In your case:

bind_rows(list_of_dataframes, .id = "column_label")

For example:

df1 <- mtcars[1:4, ]

df2 <- mtcars[11:14, ]

bind_rows(df1, df2)

Output:

   mpg   cyl  disp  hp drat    wt  qsec vs am gear carb

1 21.0   Six 160.0 110 3.90 2.620 16.46  0  1    4    4

2 21.0   Six 160.0 110 3.90 2.875 17.02  0  1    4    4

3 22.8  Four 108.0  93 3.85 2.320 18.61  1  1    4    1

4 21.4   Six 258.0 110 3.08 3.215 19.44  1  0    3    1

5 17.8   Six 167.6 123 3.92 3.440 18.90  1  0    4    4

6 16.4 Eight 275.8 180 3.07 4.070 17.40  0  0    3    3

7 17.3 Eight 275.8 180 3.07 3.730 17.60  0  0    3    3

8 15.2 Eight 275.8 180 3.07 3.780 18.00  0  0    3    3

You can read more about it here.

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...