# How to Combine Two Vectors in R

Vector manipulation forms the bedrock of R programming, serving as foundational knowledge for those aspiring to become adept at data analysis, statistical modeling, or even machine learning using R. One of the most common operations you’ll find yourself performing is combining two vectors. This article offers an exhaustive look at different techniques for achieving this, their nuances, and appropriate use-cases.

### Introduction

Vectors are one-dimensional arrays that can hold numeric data, character data, or logical data. In R, you create a vector with the c() function.

vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)

Now, let’s explore various ways to combine these vectors.

### The Basic c() Function

The simplest way to combine vectors in R is to use the c() function again.

combined_vector <- c(vector1, vector2)

This method concatenates the vectors, maintaining the original order of each vector in the new array.

### Vector Concatenation with append()

If you wish to append one vector to another but have more control over the index where the appending begins, append() comes in handy.

combined_vector <- append(vector1, vector2, after=1)

This will insert vector2 elements into vector1 starting after the first element.

### Element-wise Operations

For mathematical operations like addition or multiplication, R performs element-wise operations if both vectors are of the same length.

sum_vector <- vector1 + vector2  # c(5, 7, 9)

### Using rbind() and cbind()

The rbind() and cbind() functions are traditionally used to combine rows and columns in matrices, but they can also be used for vectors.

• rbind() combines vectors row-wise, effectively creating a matrix.
• cbind() combines vectors as different columns of a matrix.
row_combined <- rbind(vector1, vector2)
col_combined <- cbind(vector1, vector2)

### The purrr package

The purrr package offers functional programming tools for working with vectors and other data structures. Functions like map2() allow for more complex operations between two vectors.

library(purrr)
combined_vector <- map2_dbl(vector1, vector2, ~ .x + .y)

### Merging by Conditions

At times, you may wish to combine vectors based on certain conditions. Logical indexing is useful in such cases.

combined_vector <- c(vector1[vector1 > 2], vector2[vector2 > 4])

### Creating Lists

When you have vectors of different data types or lengths, you might prefer to use lists.

combined_list <- list(vector1, vector2)

### Conclusion

Combining vectors is a fundamental operation in R, and the language provides a plethora of functions to perform this task. Your choice of function will depend on various factors, including whether the vectors are of the same length or type, the desired structure of the output, and performance considerations.

Posted in RTagged