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)andc(4, 5, 6) - Output: Merged vector
c(1, 2, 3, 4, 5, 6)
Solution Steps
- Create Two Vectors: Use the
c()function to create two vectors. - Merge the Vectors: Use the
c()function to merge the two vectors into a single vector. - 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,vector1with elementsc(1, 2, 3)andvector2with elementsc(4, 5, 6).
Step 2: Merge the Vectors
- The
c()function is again used to mergevector1andvector2into a single vectormerged_vector.
Step 3: Display the Merged Vector
- The
print()function is used to display the merged vector. Thepaste()function with thecollapseargument 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.