Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like bind_rows from the dplyr package will do this too. Using maloneypatr's example:

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))

dplyr::bind_rows(df1, df2, .id = "source")

Source: local data frame [10 x 3]

#    source     a     b
#     (chr) (dbl) (dbl)
# 1       1     1    21
# 2       1     2    22
# 3       1     3    23
# 4       1     4    24
# 5       1     5    25
# 6       2     6    26
# 7       2     7    27
# 8       2     8    28
# 9       2     9    29
# 10      2    10    30

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...