Open In App

Binding rows and columns of a Data Frame in R – bind_rows() and bind_cols() Function

Last Updated : 26 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

bind_rows() function in R Programming is used to combine rows of two data frames.

Syntax:
bind_rows(data1, data2, id)

Parameter:
id: dataframe identifier
data1, data2: data frame to combine

Example: Combining Rows




# R program to illustrate
# combine rows
  
# Install dplyr package
install.packages("dplyr")  
  
# Load dplyr package                   
library("dplyr")                            
  
# Create three data frames
data1 <- data.frame(x1 = 1:5,               
                    x2 = letters[1:5])
data2 <- data.frame(x1 = 0,
                    x3 = 5:9)
data3 <- data.frame(x3 = 5:9,
                    x4 = letters[5:9])
  
# Apply bind_rows function
bind_rows(data1, data2, id = NULL)                      


Output:

    x1   x2  x3
 1   1    a  NA
 2   2    b  NA
 3   3    c  NA
 4   4    d  NA
 5   5    e  NA
 6   0    5
 7   0    6
 8   0    7
 9   0    8
 10  0    9

Here in the above code, we created 3 data frames data1, data2, data3 with rows and columns in it and then we use bind_rows() function to combine the rows that were present in the data frame. Also where the variable name is not listed bind_rows() inserted NA value.

bind_cols()

bind_cols() function is used to combine columns of two data frames.

Syntax:
bind_cols(data1, data2, id)

Parameter:
id: dataframe identifier
data1, data2: data frame to combine

Example: Combining Columns




# R program to illustrate
# combine rows
  
# Install dplyr package
install.packages("dplyr")  
  
# Load dplyr package                   
library("dplyr")                            
  
# Create three data frames
data1 <- data.frame(x1 = 1:5,               
                    x2 = letters[1:5])
data2 <- data.frame(x1 = 0,
                    x3 = 5:9)
data3 <- data.frame(x3 = 5:9,
                    x4 = letters[5:9])
  
# Apply bind_cols function
bind_cols(data1, data3, id = NULL)                      


Output:

   x1 x2 x3 x4
 1  1  a  5  e
 2  2  b  6  f
 3  3  c  7  g
 4  4  d  8  h
 5  5  e  9  i 

Here in the above code we have created 3 data frames and then combine their columns by using bind_cols() function.
Here we have combined the var. x1, x2 of data1 and x3, x4 of data2 with each other.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads