In this article we will work on how two bind two columns in R using cbind() command.
Theory
Did you ever come across a problem of binding two columns into a single table?
I’m sure you did! Especially in data analytics and data science, we often produce results in a new table (or a data frame) and the end goal is to combine it all in one table to draw meaningful insights from the results.
It is often the case that we need that result as a single unified table to produce outlines or our findings in a report.
For example, we can have a table with a list of students, and a table with their grades (assume the order of data points in each table is identical to each other).
What we want to do is to bind the result into a single table.
Below I will show an example of the usage of popular R base command cbind().
Application
Below are the steps we are going to take to make sure we do master the skill of binding two columns in R:
- Basic cbind() command description
- Creating two sample tables in R
- Binding two columns in R
Part 1. Basic cbind() command description
The short theoretical explanation of the function is the following:
cbind(objects1, object2, …)
Here, “object” refers to either a table, or a data frame, or any other data structure you would like to bind.
In our example, there will be two objects “students” and “grades”. But you can always bind more than two objects.
Part 2. Creating two sample tables in R
For the purpose of this article, we will create two data frames. The first one will be a list of names of four students. The second one will be a list of their grades for an exam.
You can create these sample data frames using the following code:
students<-data.frame(first_name=c("John", "Eric", "Samuel", "David"))
grades<-data.frame(mark=c("86%", "72%", "94%", "84%"))
Now, we can take a look at the two data frames we just created:
View(students)
View(grades)
Note: in this article I create my own datasets. If you have your own in a csv or excel files, you can follow the same procedure to arrive at the result.
Part 3. Binding two columns in R
Our goal now is to create a new data frame (table) "report" where we will have both "students" and "grades" binded.
This is the part of the article where we will see an applied example on how to bind two columns in R.
As discussed above, "students" and "grade" will be our "objects" for the cbind() command.
At this point, we are all set to bind two columns in R!
You can do it using the following code:
report<-cbind(students, grades)
You can take a look at the edited table by using this command:
View(report)
If you are interested to learn more about data manipulation in R, you can find more articles here.