How to Combine Two Vectors in R (With Examples)

R is a programming language that allows you to combine two vectors together. This can be done by using the c() function to combine the two vectors into a single vector. This can be useful for creating a data set or performing calculations with multiple vectors. Examples of how to combine two vectors are provided in this article.


You can use one of the following methods to combine two vectors in R:

Method 1: Combine Two Vectors Into One Vector

new_vector <- c(vector1, vector2)

Method 2: Combine Two Vectors Into a Matrix

new_matrix <- cbind(vector1, vector2)

Method 3: Combine Two Vectors Into a Data Frame

new_df <- data.frame(vector1, vector2)

The following examples show how to use each method in practice.

Method 1: Combine Two Vectors Into One Vector

The following code shows how to combine two vectors into one new vector:

#define vectors
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(6, 7, 8, 9, 10)

#combine two vectors into one vector
new_vector <- c(vector1, vector2)

#view resulting vector
new_vector

[1]  1  2  3  4  5  6  7  8  9 10

Method 2: Combine Two Vectors Into a Matrix

The following code shows how to combine two vectors into a matrix:

#define vectors
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(6, 7, 8, 9, 10)

#combine two vectors into matrix
new_matrix <- cbind(vector1, vector2)

#view resulting matrix
new_matrix

     vector1 vector2
[1,]       1       6
[2,]       2       7
[3,]       3       8
[4,]       4       9
[5,]       5      10

Related:

Method 3: Combine Two Vectors Into a Data Frame

The following code shows how to combine two vectors into a data frame:

#define vectors
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(6, 7, 8, 9, 10)

#combine two vectors into data frame
new_df <- data.frame(vector1, vector2)

#view resulting data frame
new_df

  vector1 vector2
1       1       6
2       2       7
3       3       8
4       4       9
5       5      10

Notice that each original vector is now a unique column in the resulting data frame.

The following tutorials explain how to perform other common operations in R:

x