R rbind() and cbind() Functions - Row and Column Combination
The R rbind() function combines data by row, while cbind() combines data by column.
They can combine vectors, matrices, and data frames, and are fundamental operations for building data structures.
The syntax of the two functions is as follows:
rbind(...) # 按行合并(row bind)
cbind(...) # 按列合并(column bind)
Parameter Description:
-
... The vectors, matrices, or data frames to combine.
Example
cbind: combine vectors by column
name
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
)
age
<-
c
(
25
,
30
,
28
)
score
<-
c
(
88
,
92
,
76
)
Combine into a matrix
mat
<-
cbind
(
name, age, score
)
(
"cbind combined into a matrix:"
)
(
mat
)
rbind: combine by row
row1
<-
c
(
"A"
,
"B"
,
"C"
)
row2
<-
c
(
"D"
,
"E"
,
"F"
)
result
<-
rbind
(
row1, row2
)
(
"rbind combined by row:"
)
(
result
)
The output of the code above is:
[1] "cbind 合并为矩阵:"
name age score
[1,] "张三" "25" "88"
[2,] "李四" "30" "92"
[3,] "王五" "28" "76"
[1] "rbind 按行合并:"
[,1] [,2] [,3]
row1 "A" "B" "C"
row2 "D" "E" "F"
In data analysis, rbind() is often used to append data rows:
Example
Original data frame
df
<-
data.frame
(
Name
=
c
(
"Zhang San"
,
"Li Si"
)
,
Age
=
c
(
25
,
30
)
,
stringsAsFactors
=
FALSE
)
(
"Original:"
)
(
df
)
Append a new row
new_student
<-
data.frame
(
Name
=
"Wang Wu"
,
Age
=
28
,
stringsAsFactors
=
FALSE
)
df_new
<-
rbind
(
df
, new_student
)
(
"After appending:"
)
(
df_new
)
The output of the code above is:
[1] "原始:"
姓名 年龄
1 张三 25
2 李四 30
[1] "追加后:"
姓名 年龄
1 张三 25
2 李四 30
3 王五 28
R Language Examples