SoFunction
Updated on 2025-03-01

The use and difference between cbind, rbind and merge functions in R language

cbind: Merge according to the column, that is, superimpose all columns. The matrix of m column and the matrix of n columns cbind() finally become m+n columns. The prerequisite for merging: the number of rows of matrices a and c in cbind(a, c) must match the number of rows of matrices a and c in cbind(a, c)

rbind: Merge according to rows, that is, superposition of rows. The matrix of m rows and n rows of matrix rbind() finally becomes m+n rows. The prerequisite for merging: the number of columns of matrices a and c in rbind(a, c) must match the number of columns of matrices a and c in rbind(a, c)

> a <- matrix(1:12, 3, 4)
> print(a)
   [,1] [,2] [,3] [,4]
[1,]  1  4  7  10
[2,]  2  5  8  11
[3,]  3  6  9  12
> 
> b <- matrix(-1:-12, 3, 4)
> print(b)
   [,1] [,2] [,3] [,4]
[1,]  -1  -4  -7 -10
[2,]  -2  -5  -8 -11
[3,]  -3  -6  -9 -12
> 
> x=cbind(a,b)
> print(x)
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]  1  4  7  10  -1  -4  -7 -10
[2,]  2  5  8  11  -2  -5  -8 -11
[3,]  3  6  9  12  -3  -6  -9 -12
> 
> y=rbind(a,b)
> print(y)
   [,1] [,2] [,3] [,4]
[1,]  1  4  7  10
[2,]  2  5  8  11
[3,]  3  6  9  12
[4,]  -1  -4  -7 -10
[5,]  -2  -5  -8 -11
[6,]  -3  -6  -9 -12
> 
> 
> c <- matrix(-1:-20, 4, 5)
> print(c)
   [,1] [,2] [,3] [,4] [,5]
[1,]  -1  -5  -9 -13 -17
[2,]  -2  -6 -10 -14 -18
[3,]  -3  -7 -11 -15 -19
[4,]  -4  -8 -12 -16 -20
> 
> x2=cbind(a,c)
Error in cbind(a, c) : The number of rows of the matrix must match(Seearg2)
> print(x2)
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]  1  4  7  10  -1  -4  -7 -10 -13
[2,]  2  5  8  11  -2  -5  -8 -11 -14
[3,]  3  6  9  12  -3  -6  -9 -12 -15
> 
> y2=rbind(a,c)
Error in rbind(a, c) : The number of columns of the matrix must match(Seearg2)
> print(y2)
Error in print(y2) : The object cannot be found'y2'
> 

merge function

Two data frames have the same time or observations, but the columns are not the same. The way to deal with it is to use
merge(x, y, = , = , all = ) function.

#merge/mergeID<-c(1,2,3,4)
name<-c(“A”,”B”,”C”,”D”)
score<-c(60,70,80,90)
student1<-(ID,name)
student2<-(ID,score)
total_student1<-merge(student1,student2,by=”ID”)
total_student1

When we need to merge different types of variables derived from the same observation object, cbind is used, that is, merging column.

This is the article about the use and differences between cbind, rbind and merge functions in R language. For more related content in R language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!