cbind: 根据列进行合并,即叠加所有列,m列的矩阵与n列的矩阵cbind()最后变成m+n列,合并前提:cbind(a, c)中矩阵a、c的行数必需相符
rbind: 根据行进行合并,就是行的叠加,m行的矩阵与n行的矩阵rbind()最后变成m+n行,合并前提:rbind(a, c)中矩阵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) : 矩阵的行数必需相符(见arg2) > 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) : 矩阵的列数必需相符(见arg2) > print(y2) Error in print(y2) : 找不到对象'y2' >
merge函数
两个数据框拥有相同的时间或观测值,但这些列却不尽相同。处理的办法就是使用
merge(x, y ,by.x = ,by.y = ,all = ) 函数。
#merge/合并 ID<-c(1,2,3,4) name<-c(“A”,”B”,”C”,”D”) score<-c(60,70,80,90) student1<-data.frame(ID,name) student2<-data.frame(ID,score) total_student1<-merge(student1,student2,by=”ID”) total_student1
当我们需要将相同的观测对象得出的不同类型变量合并时,则采用cbind,也就是合并columm。