How to Combine Two Vectors in R (With Examples)


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: How to Use cbind in R (With Examples)

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.

Additional Resources

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

How to Combine Lists in R
How to Combine Two Columns into One in R
How to Combine Two Data Frames in R with Different Columns

Leave a Reply

Your email address will not be published.