R Data Frame: Add Data with rbind & cbind

In R language, you can add data to a data frame by using the following method:

  1. You can use the rbind() function to add new data to the end of a data frame. For example:
# 创建一个数据框
df <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"))

# 添加新的数据到数据框
new_data <- data.frame(A = 4, B = "d")
df <- rbind(df, new_data)
  1. By using the cbind() function, you can add new data to the end of a data frame’s columns. For example:
# 创建一个数据框
df <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"))

# 添加新的数据到数据框
new_data <- c(4, "d")
df <- cbind(df, new_data)
  1. You can add data directly by using the $ symbol to specify column names and row indices. For example:
# 创建一个数据框
df <- data.frame(A = c(1, 2, 3), B = c("a", "b", "c"))

# 添加新的数据到数据框
df$A[4] <- 4
df$B[4] <- "d"

Here are some simple ways to add data to a data frame, and these methods can be adjusted based on your needs and data structure.

bannerAds