2

Suppose I have three datasets

DF1=
Traj X Y
1   4 5
1   7 8
2   5 6
DF2=

Traj X Y
1   5 2
1   6 4
2   8 7
DF3=

Traj X Y
1   8 5
1   1 9
2   3 7

How can I combine them into one dataset like below:

DF1=

Traj X Y
1   4 5
1   7 8
2   5 6
1   5 2
1   6 4
2   8 7
1   8 5
1   1 9
2   3 7

I have many similar data that have similar elements and it would be easier to just combine them, unfortunately I don't know how to do so.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
damien
  • 69
  • 4

4 Answers4

3

In base R, rbind(DF1, DF2, DF3 (rbind stands for "row bind", i.e. "put rows together"). In tidyverse, dplyr::bind_rows(DF1, DF2, DF3) is slightly fancier.

If you already have a list of your data frames,

DFlist <- list(DF1, DF2, DF3)
do.call(DFlist, rbind)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
2

Simply do this

rbind(df1, df2, df3) 
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
2

Another option is to place it in a list and use bind_rows

library(dplyr)
mget(ls(pattern = '^DF\\d+$')) %>%
       bind_rows
akrun
  • 874,273
  • 37
  • 540
  • 662
2

This works also:

bind_rows(DF1, DF2, DF3)
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • how does this add to/differ from previously posted answers by me and @akrun? – Ben Bolker Mar 21 '21 at 18:22
  • See here: . At the time of my post I did not recognize the `bind_rows` from akrun. But anyway you can simply use `bind_rows` without `mget` . – TarJae Mar 21 '21 at 18:28
  • 1
    My answer already refers to `bind_rows()` (in the second sentence), although it is not *quite* as explicitly stated as your answer. (I just edited my answer to make the implicit "`bind_rows` is called in the same way as `rbind`" more explicit ...) – Ben Bolker Mar 21 '21 at 18:31
  • Yes you are right Ben. But it was not a bad intention. I just read over the part with `bind_rows` in your post. Sorry for that. I have voted up your answer at the time I posted mine. – TarJae Mar 21 '21 at 18:39
  • 1
    That makes sense. I'm not downvoting your answer, just hesitating to upvote it. – Ben Bolker Mar 21 '21 at 18:42
  • Thanks Ben. Will take more care in future! – TarJae Mar 21 '21 at 18:43