6.1 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Combine Two Vectors in R (With Examples)

How to Combine Two Vectors in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Method 1: Combine Two Vectors Into One Vector

new_vector 

Method 2: Combine Two Vectors Into a Matrix

new_matrix 

Method 3: Combine Two Vectors Into a Data Frame

new_df 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 #combine two vectors into one vector
new_vector #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 #combine two vectors into matrix
new_matrix #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 #combine two vectors into data frame
new_df 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories