R rbind() and cbind() functions - Row and column merging

R 语言实例R Language Examples

The R rbind() function is used to combine data by rows, and cbind() is used to combine data by columns.

They can combine vectors, matrices, and data frames, and are fundamental operations for constructing data structures.

The syntax of the two functions is as follows:

rbind(...)   # 按行合并(row bind)
cbind(...)   # 按列合并(column bind)

Parameter description:

  • ...Vectors, matrices, or data frames to be combined.

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)
print("cbind combined into matrix:")
print(mat)

# rbind: combine by row
row1 <- c("A", "B", "C")
row2 <- c("D", "E", "F")
result <- rbind(row1, row2)
print("rbind combined by row:")
print(result)

Executing the above code outputs the following:

[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
)
print("Original:")
print(df)

# Append a new row
new_student <- data.frame(
Name= Wang Wu,
Age= 28,
  stringsAsFactors = FALSE
)
df_new <- rbind(df, new_student)
print("After appending:")
print(df_new)

Executing the above code outputs the following:

[1] "原始:"
  姓名 年龄
1 张三   25
2 李四   30
[1] "追加后:"
  姓名 年龄
1 张三   25
2 李四   30
3 王五   28

R 语言实例R Language Examples

Other Extensions