cbind

cbind(x1,x2,...)
cbind() function is used for combining vector, matrix or data frame by columns.

Example

It only makes sense to merge by column if the two data sets have the same number of rows. Unlike the rbind() command, the columns don't need to be same in cbind. Columns can be different, but the number of rows in both the data sets must be the same.

x1,x2: These can be vectors, matrices or data frames

First, let us create two data frames so that we can run the cbind() function on them. we are going to create data frames with 3 rows each. Both of them contain different columns.

 #Preparing a data frame with 3 rows
 firstName <- c("Ethan", "John", "Selina")
 lastName <- c("Hunt", "Whick", "Kyle")
 sex <- c("MALE", "MALE", "FEMALE")
 score <- c(97, 88, 85)
 stu_df1 <- data.frame(firstName, lastName, sex, score)
 stu_df1
 #preparing another data frame with 3 rows
 surName <- c("Hunt", "Whick", "Kyle")
 hairColor <- c("Black", "Black", "Red")
 age <- c(40, 42, 24)
 stu_df2 <- data.frame(surName, hairColor, age)
 stu_df2

Now to combine the data by columns, we simply need to use cbind on these two frames.

 firstName <- c("Ethan", "John", "Selina")
 lastName <- c("Hunt", "Whick", "Kyle")
 sex <- c("MALE", "MALE", "FEMALE")
 score <- c(97, 88, 85)
 stu_df1 <- data.frame(firstName, lastName, sex, score)
 surName <- c("Hunt", "Whick", "Kyle")
 hairColor <- c("Black", "Black", "Red")
 age <- c(40, 42, 24)
 stu_df2 <- data.frame(surName, hairColor, age)
 cbind(stu_df1,stu_df2)

Even if the columns have the same names, that would not be an issue as column names don't need to be unique.

Let us see what happens if one of the data frames has fewer rows.

 firstName <- c("Ethan", "John", "Selina")
 lastName <- c("Hunt", "Whick", "Kyle")
 sex <- c("MALE", "MALE", "FEMALE")
 score <- c(97, 88, 85)
 stu_df1 <- data.frame(firstName, lastName, sex, score)
 lastName <- c("Hunt", "Whick")
 hairColor <- c("Black", "Black")
 age <- c(40, 42)
 stu_df2 <- data.frame(lastName, hairColor, age)
 cbind(stu_df1,stu_df2)

You should get an error saying that the number of rows are not equal in the data sets that are used in cbind.

If you want to add a column to the data frame (a constant value column to be specific) you can do that using cbind. You can pass that value with the data frame to cbind as follows.

 firstName <- c("Ethan", "John", "Selina")
 lastName <- c("Hunt", "Whick", "Kyle")
 sex <- c("MALE", "MALE", "FEMALE")
 score <- c(97, 88, 85)
 stu_df1 <- data.frame(firstName, lastName, sex, score)
 Adding a constant value column
 cbind(stu_df1,"Human")

A new column gets added at the end of the frame.

cbind is analogous to Joins in SQL.