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

Dataframes: cbind

- [Narrator] So, let's talk about combining data frames. And you can combine data frames top to bottom with the rbind command. Or you can combine data frames side by side with the cbind command. And let's talk about cbind or column bind. First, we need a little bit of source data, so let's just pull in source makeChickWeight. And I run that. And that produces a bunch of data frames that we'll use to experiment with. Now, let's take a look at chick_one, and you can see that we have four columns, four variables, and twelve observations, or twelve rows. We can also take a look at chicknames. And, if we look at chicknames, you'll see that we have rank and a name and, if we go all the way down, then there's Hulk and Peter and Arianna. So, we have 50 rows in chicknames. Now, let's take a look at ChickWeight as well. ChickWeight has the same four columns, it has 578 rows. So, let's combine ChickWeight with chicknames using cbind. And, to do that, we will create a new data framed. And we'll call it cbind_chicknames. And into that we will cbind... two data frames. And the first one we'll pull up is ChickWeight, there it is, and I want to grab the first 50 rows. So, to do that, I'll use the bracket and one colon 50 and I'm going to grab rows, I'm going to leave the columns alone. So, you'll notice that it's one colon 50 comma space, and that's a subsetting command to pull in the first 50 rows and all of the columns. And I'm going to combine that with chicknames, there it is right there. So, I can run that command hitting Command + Return. And if we now look at that new data frame, what we'll see is, we have the original four columns, plus two new columns, rank and name, and, again, the four columns in ChickWeight, and then here's chicknames. And there's the combined data frames. Now, the number of rows is important when you're combining with cbind, and I can demonstrate that. Let's pull up the exact same command that I just used, and I'm going to copy and paste that. And I'm going to remove the subset of the rows, so now what I have is the entire 578 rows of ChickWeight with 50 rows of chicknames. When I run this, Command + Return, you'll see that I get an error message. And the arguments imply differing numbers of rows. It tells ChickWeight has 578 and chicknames has 50. So, the important takeaway here is that when you're using cbind, the number of rows need to be the same.

Contents