R Program to Concatenate Two Vectors

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

1. Introduction

Vectors are a fundamental data structure in R, used to store an ordered collection of items, typically numbers or characters. There are times when you might want to combine or concatenate two vectors to form a single one. In R, this can be easily achieved using the c() function.

2. Program Overview

This post will walk you through a simple R program that concatenates two vectors. We'll utilize R's inbuilt functions and understand each step involved.

3. Code Program

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

# Concatenate the vectors
concatenated_vector <- c(vector1, vector2)

# Display the concatenated vector
print(concatenated_vector)

Output:

[1] 1 2 3 4 5 6

4. Step By Step Explanation

1. We start by creating two sample vectors, vector1 and vector2, using the c() function. Here, vector1 contains the elements 1, 2, and 3, while vector2 contains the elements 4, 5, and 6.

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

2. To concatenate the vectors, we again use the c() function, passing in both vectors as arguments. This will combine the elements of both vectors into a single vector. The result is stored in the concatenated_vector variable.

# Concatenate the vectors
concatenated_vector <- c(vector1, vector2)

3. Finally, we use the print() function to display the concatenated_vector, which now holds the elements from both original vectors in the order they were provided.

# Display the concatenated vector
print(concatenated_vector)

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare