Append two data frames on top of each other

ledzep

Point Mass at Zero
#1
Dear all,

I have two data frames. Both have same column names but the rows are entirely different. So, I want to stack the data frames on top of each other. How do I get this done?

Many Thanks.
 

trinker

ggplot2orBust
#3
You could also covert each row to a vector, break the individual cells up into a list then unlist all the lists into a big vector then form a large matrix with the correct dimensions and then give row and column names and then use as.data.frame() but I'm pretty sure rbind is a substantially better choice.
 

Dason

Ambassador to the humans
#4
You just got me thinking about the most convoluted way to do this possible. I had an idea involving creating a linear model that you could use predict on to get the data frame of interest...
 

ledzep

Point Mass at Zero
#5
Many Thanks all. I was exploring different ways, and through trial and error, I ended up doing this in a slightly different way though.

I found that merge works fine. As long as both data have exactly identical column names, using merge worked wonders but had to use all.x=T and all.y=T option. Methinks it is a cute little way to append two data frames.

Myself being a newbie to R, I might be jumping guns here. So, please warn me if this doesn't always work.

Code:
merged_dataframe<-merge(df1,df2, all.x=TRUE, all.y=TRUE)
 

Dason

Ambassador to the humans
#6
Is there something wrong with rbind for your situation? I have a hunch rbind would be a lot more efficient if all you're looking to do is stack two dataframes.
 

ledzep

Point Mass at Zero
#7
rbind works perfectly fine. Just the fact that I was overexcited in finding an alternative solution by myself which I couldn't resist sharing.:)
 

Dason

Ambassador to the humans
#8
You would want to be careful with your method. rbind will literally just paste the two dataframes together. Merge takes into consideration whether a row is replicated or not.

Here is some example code to show you that you won't always get the same thing with both methods.
Code:
df1 <- data.frame(name = c("tim", "tim", "tim", "ron"), val = 1:4)
df2 <- data.frame(name = c("tim", "tim", "ron","ron"), val = 1:4)

df1
df2
rbind(df1, df2)
merge(df1, df2, all.x = T, all.y =T)
 

ledzep

Point Mass at Zero
#9
Many Thanks Dason for the useful post. I wasn't aware of this pitfall of using merge. Luckily, in my case, the rows were unique.
Certainly,something to be aware of! (I was indeed jumping guns!)