R Program to Merge Two Vectors

Introduction

Merging vectors is a common operation in data manipulation, where you combine elements from two or more vectors into a single vector. This guide will walk you through writing an R program that merges two vectors.

Problem Statement

Create an R program that:

  • Creates two vectors.
  • Merges the two vectors into one.
  • Displays the merged vector.

Example:

  • Input: Two vectors c(1, 2, 3) and c(4, 5, 6)
  • Output: Merged vector c(1, 2, 3, 4, 5, 6)

Solution Steps

  1. Create Two Vectors: Use the c() function to create two vectors.
  2. Merge the Vectors: Use the c() function to merge the two vectors into a single vector.
  3. Display the Merged Vector: Use the print() function to display the merged vector.

R Program

# R Program to Merge Two Vectors
# Author: https://www.javaguides.net/

# Step 1: Create two vectors
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)

# Step 2: Merge the two vectors
merged_vector <- c(vector1, vector2)

# Step 3: Display the merged vector
print(paste("Merged vector:", paste(merged_vector, collapse = ", ")))

Explanation

Step 1: Create Two Vectors

  • The c() function is used to create two vectors, vector1 with elements c(1, 2, 3) and vector2 with elements c(4, 5, 6).

Step 2: Merge the Vectors

  • The c() function is again used to merge vector1 and vector2 into a single vector merged_vector.

Step 3: Display the Merged Vector

  • The print() function is used to display the merged vector. The paste() function with the collapse argument is used to format the vector elements into a comma-separated string for display.

Output Example

Example:

[1] "Merged vector: 1, 2, 3, 4, 5, 6"

Conclusion

This R program demonstrates how to merge two vectors into a single vector. It covers basic vector operations such as creation and merging, making it a useful example for beginners learning R programming. Understanding how to combine vectors is essential for data manipulation and preparation in various analyses.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top