cbind() in R – Column bind with bind_cols() function

Column Bind – Cbind  in R appends or combines vector, matrix or data frame by columns. cbind() function in R appends or joins, two or more dataframes in column wise. same column bind operation can also be performed using bind_cols() function of the dplyr package.  Lets see column bind in R which emphasizes on bind_cols() function and cbind() function with an example for each.

In this Tutorial we will look at

  • Example of column bind operation in R by using cbind() function.
  • How to perform column bind operation using bind_cols() function of dplyr package
  • Whats is difference between cbind() function and bind_cols() Function with an example.

The pictographical representation of column bind operation is shown below. It is simple concatenate of the two or more tables on column wise.

column-binding

Note : The number of rows in two dataframes needs to be same for both cbind() function and bind_cols() function.

 

Syntax for cbind() in R:

cbind(x1,x2)

x1,x2 can be data frame, matrix or vector.

Example of Cbind in R:

Lets see how to implement cbind() function in R with an example. First lets create two data frames

#Create two data frames
df1 = data.frame(name = c("Rahul","joe","Adam","Brendon"), married_year = c(2016,2015,2016,2008))
df1
df2 = data.frame(Birth_place = c("Delhi","Seattle","London","Moscow"), Birth_year = c(1988,1990,1989,1984))
df2
df1 will be 

column bind in r cbind 2

  df2 will be 

column bind in r cbind 3

Now, column bind (cbind) concatenates or joins these two data frames column wise as shown below. cbind() function takes two dataframes as argument and results in the appended or column binded dataframe. The number of rows in two dataframes needs to be same for both cbind() function

# cbind in R: column bind the data frames.
cbinded_df = cbind(df1,df2)
cbinded_df

so the resultant column bind data frame in R will be
column bind in r cbind 4

 

 

Column Bind in R using bind_cols() function of Dplyr()

Syntax for bind_cols() in R:

bind_cols(x1,x2)

x1,x2 are the data frames

Now, bind_cols() function of dplyr, takes two dataframes df1 and df2 as argument and the results are appended or column binded to a data frame as shown below. The number of rows in two dataframes needs to be same for  bind_cols() function.

# bind_cols in R: column bind the data frames.

library(dplyr)
colbinded_df = bind_cols(df1,df2)
colbinded_df

so the resultant column bind data frame by using bind_cols() function will be

column bind in r cbind 4

cbind() function and bind_cols() Function performs in the similar manner and can be used alternatively for column binding. For Further understanding on bind_cols() function refer r dplyr package document.

cbind function in r                                                                                                           cbind in R