1

I have 3 data frames in R lets say:

df1 <- data.frame(x = 1:5, y = 1:5)
df2 <- data.frame(x = 1:6, y = 1:6)
df3 <- data.frame(x = 1:4, y = 1:4)

and I would like to merge them together to create a new data frame that would have as first column the name of the data frame for each row of that data frame. I would look like this:

   df x y
1  df1 1 1
2  df1 2 2
3  df1 3 3
4  df1 4 4
5  df1 5 5
6  df2 1 1
7  df2 2 2
8  df2 3 3
9  df2 4 4
10 df2 5 5
11 df2 6 6
12 df3 1 1
13 df3 2 2
14 df3 3 3
15 df3 4 4

Any ideas? Thank you in advance.

tjebo
  • 21,977
  • 7
  • 58
  • 94
NewtonsGate
  • 31
  • 1
  • 3

3 Answers3

2

Use bind_rows from the dplyr package. This will work with arbitrary numbers of data frames. The ls call gets all the variables in the namespace that begin with 'df'; mget gives you a named list of the data frames. The .id argument lets you specify column name.

df_out <- bind_rows(mget(ls(pattern='df')), .id='df')

Output is as follows:

    df x y
1  df1 1 1
2  df1 2 2
3  df1 3 3
4  df1 4 4
5  df1 5 5
6  df2 1 1
7  df2 2 2
8  df2 3 3
9  df2 4 4
10 df2 5 5
11 df2 6 6
12 df3 1 1
13 df3 2 2
14 df3 3 3
15 df3 4 4
Edward Carney
  • 1,372
  • 9
  • 7
1

Here's a simple and very basic approach:

rbind(df1=df1,df2=df2,df3=df3)

The result:

      x y
df1.1 1 1
df1.2 2 2
df1.3 3 3
df1.4 4 4
df1.5 5 5
df2.1 1 1
df2.2 2 2
df2.3 3 3
df2.4 4 4
df2.5 5 5
df2.6 6 6
df3.1 1 1
df3.2 2 2
df3.3 3 3
df3.4 4 4
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
1

Sticking with base R functions and expanding on NelsonGon's answer a little:

d <- rbind(df1=df1, df2=df2, df3=df3)
d <- cbind(df=sub("..$", "", rownames(d)), data.frame(d, row.names=NULL))
d
    df x y
1  df1 1 1
2  df1 2 2
3  df1 3 3
4  df1 4 4
5  df1 5 5
6  df2 1 1
7  df2 2 2
8  df2 3 3
9  df2 4 4
10 df2 5 5
11 df2 6 6
12 df3 1 1
13 df3 2 2
14 df3 3 3
15 df3 4 4

This uses cbind to add modified rownames as a column.

makeyourownmaker
  • 1,558
  • 2
  • 13
  • 33