From the course: R for Data Science: Lunch Break Lessons

Data frames: rbind

- So let's talk about combining data frames and we'll talk about something called rbind. Rbind is a lot like an SQL Union, where you combine one data frame on top of another. And to illustrate this, we need a little bit of sample data, so I'm going to source a file called makeChickWeight.R, and that brings in four data frames. Let's take a look at one of 'em real quick. Here's chick.one, and we have four columns and 12 rows. Chick.two is almost identical, the data is just a little bit different. So, I would like to combine chick.one and chick.two, into a new data frame and to do that, what I'll do here is go back to our source file, and I'll type in the command for it. Which is chick.one.and.chick.two and I'll assign it, in that we're going to use the rbind, R-B-I-N-D command. And with rbind, I tell it what I want to combine. So I'll type in chick.one, and chick.two. And I hit Command + Return, and what I find is is I now have a new data frame, it has 24 observations instead of 12. And if we look at that data frame, you'll see there are 24 rows. It's just simply chick.one glued on top of chick.two. That's the core of rbind. There is a couple of tricks to know about. And one of them is is that rbind really insists that the column names are the same. So let's illustrate that. Let's rename chick.one. We'll create a new data frame. And chick.one renamed will now have new names. So let's take a look at that. So here's chick.one.renamed, you can see chick.one is now named grams, and chronos, and subject, and food. Chick.two, is weight, time, chicken, diet. Now if I come down here, and we'll try to combine those two. So let's go chicks.one.and.two, and into that we'll use rbind, and we're going to combine chick.one.renamed, and we're going to combine that with chick.two. So let's run that. Now what I'll get is an error message. And what it's telling me is that the names do not match the previous name. So, if I rename columns, rbind is not going to be able to figure out which column to paste on top of which other column. So keep in mind when you're using rbind. That it's like an SQL Union. Rbind combines one data frame on top of another, and the column names need to be identical.

Contents