cbind Function in R (Example)
This article explains how to column bind a data frame and a vector with the cbind function in the R programming language.
Example Data
In this example, we use the following data frame:
my_data <- data.frame(x1 = 1:5, # Create first data frame x2 = letters[1:5]) my_data # x1 x2 # 1 a # 2 b # 3 c # 4 d # 5 e |
my_data <- data.frame(x1 = 1:5, # Create first data frame x2 = letters[1:5]) my_data # x1 x2 # 1 a # 2 b # 3 c # 4 d # 5 e
We also use the following vector:
my_vec <- c(9, 1, 8, 2, 5) # Create vector my_vec # 9 1 8 2 5 |
my_vec <- c(9, 1, 8, 2, 5) # Create vector my_vec # 9 1 8 2 5
Note that the number of rows of our data frame and the length of our vector needs to be the same.
Application of cbind Function in R
We can combine our data frame and our vector by column with the cbind function as shown below:
combined_data <- cbind(my_data, my_vec) # Apply cbind function combined_data # x1 x2 my_vec # 1 a 9 # 2 b 1 # 3 c 8 # 4 d 2 # 5 e 5 |
combined_data <- cbind(my_data, my_vec) # Apply cbind function combined_data # x1 x2 my_vec # 1 a 9 # 2 b 1 # 3 c 8 # 4 d 2 # 5 e 5