I have several data frames with the same columns and I would like to combine them in such a way that identifies which data frame they are from. For example, if in data frame #1, I have this data:
x y
1 a 1
2 b 4
And in data frame #2, I have this data:
x y
1 d 6
2 e 7
I would like to combine them into one data frame with a new column that identifies which data frame they came from:
frame x y
1 1 a 1
2 1 b 4
3 2 d 6
4 2 e 7
The frame column identifies that rows 1 and 2 are from data frame #1, and rows 3 and 4 are from data frame #2. I'm using strings to identify my data frames, but I just used numbers here to make the example simpler.
Using the same list approach as @Shambho with do.call:
dfList <- list(
df1 = data.frame(x=letters[1:2],y=1:2),
df2 = data.frame(x=letters[3:4],y=3:4)
)
data.frame(
frame = rep(seq_along(dfList), sapply(dfList, nrow)),
do.call(rbind, dfList), row.names=NULL
)
## frame x y
## 1 1 a 1
## 2 1 b 2
## 3 2 c 3
## 4 2 d 4
Or like this?:
Assuming df1 and df2 are your data frame 1 and 2, respectively:
data.frame(frame=rep(1:2,lapply(list(df1,df2),function(x) dim(x)[1])),rbind(df1,df2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With