Introduction
Vectors are one of the most basic data structures in R, used to store a sequence of elements of the same type. This guide will walk you through writing an R program to create a vector and access its elements.
Problem Statement
Create an R program that:
- Creates a vector with a sequence of elements.
- Accesses and displays specific elements of the vector.
Example:
- Input: A vector with elements
1, 2, 3, 4, 5
- Output: Elements at specific positions, such as the 2nd and 4th elements.
Solution Steps
- Create a Vector: Use the
c()
function to create a vector with a sequence of elements. - Access Elements of the Vector: Use indexing to access specific elements of the vector.
- Display the Accessed Elements: Use the
print()
function to display the elements retrieved from the vector.
R Program
# R Program to Create and Access Elements of a Vector
# Author: https://www.javaguides.net/
# Step 1: Create a vector with a sequence of elements
my_vector <- c(1, 2, 3, 4, 5)
# Step 2: Access specific elements of the vector
second_element <- my_vector[2]
fourth_element <- my_vector[4]
# Step 3: Display the accessed elements
print(paste("Second element:", second_element))
print(paste("Fourth element:", fourth_element))
Explanation
Step 1: Create a Vector
- The
c()
function is used to create a vector with the elements1, 2, 3, 4, 5
.
Step 2: Access Specific Elements
- Vectors in R are 1-indexed, meaning that the first element is accessed with index
1
. my_vector[2]
retrieves the second element of the vector.my_vector[4]
retrieves the fourth element of the vector.
Step 3: Display the Accessed Elements
- The
print()
function is used to display the retrieved elements along with a descriptive message.
Output Example
Example:
[1] "Second element: 2"
[1] "Fourth element: 4"
Conclusion
This R program demonstrates how to create a vector and access specific elements by indexing. It covers basic operations such as vector creation and element retrieval, making it an essential example for beginners learning R programming.