Create a variable that identifies the original data.frame after rbind command in R

loops, r, rbind

Solution

There's a function in the `gdata` package called `combine` that does just that.

df1 <- data.frame(a = seq(1, 5, by = 1),
                  b = seq(21, 25, by = 1))

df2 <- data.frame(a = seq(6, 10, by = 1),
                  b = seq(26, 30, by = 1))

library(gdata)
combine(df1, df2)

    a  b source
1   1 21    df1
2   2 22    df1
3   3 23    df1
4   4 24    df1
5   5 25    df1
6   6 26    df2
7   7 27    df2
8   8 28    df2
9   9 29    df2
10 10 30    df2

Problem

I am relatively new to R and I would like to know how can I create a variable (number sequence) that identifies the each of the original data.frames before being joined with the rbind command. Since in the original data frames there is one variable that is a row ID number, if creating a loop that assigns a new number in the new variable each time it encounters the number 1 in the row ID, it should work... Thanks.

Original source