Accessing and modifying element of a vector

Introduction

Vectors in R are ordered data structures in which each element occupies a fixed position. The process of extracting or altering values relies on the language’s 1‑based indexing system. In this system, the first element of a vector is referenced by index 1, the second by index 2, and so forth. This indexing approach is essential to understand, especially because it differs from languages such as Python that follow 0‑based indexing.


1. Indexing Structure in R

Indexing in R is carried out using square brackets [ ]. The index placed inside the brackets determines which element or group of elements is accessed. When a vector is created, R assigns sequential positions beginning from 1.

Example: Creating a Vector

my_vec1 <- c(1, 2, 3, 4, 5)

Element positions:
1 → index 1
2 → index 2
3 → index 3
4 → index 4
5 → index 5


2. Accessing Elements of a Vector

Access operations return the value stored at the given index.

2.1 Accessing a Single Element

my_vec1[1]

Output:

[1] 1

2.2 Accessing Another Element

my_vec1[4]

Output:

[1] 4

2.3 Accessing Multiple Elements

my_vec1[c(1, 3, 5)]

Output:

[1] 1 3 5

2.4 Accessing a Sequence of Elements

my_vec1[2:4]

Output:

[1] 2 3 4

2.5 Accessing Elements Using Negative Indexing

my_vec1[-3]

Output:

[1] 1 2 4 5

The element at index 3 is excluded.


3. Modifying Elements of a Vector

Modification assigns new values to one or more indexed positions.

3.1 Modifying a Single Element

my_vec1[1] <- 10
my_vec1

Output:

[1] 10 2 3 4 5

3.2 Modifying Another Element

my_vec1[5] <- 50
my_vec1

Output:

[1] 10 2 3 4 50

3.3 Modifying Multiple Elements

my_vec1[c(2, 4)] <- c(20, 40)
my_vec1

Output:

[1] 10 20 3 40 50

3.4 Modifying a Range of Elements

my_vec1[1:3] <- c(100, 200, 300)
my_vec1

Output:

[1] 100 200 300 40 50

3.5 Conditional Modification

my_vec1[my_vec1 > 100] <- 999
my_vec1

Output:

[1] 999 999 999 40 50

Values exceeding 100 are replaced.


4. Significance of Index-Based Access

Indexing allows precise extraction and modification of vector elements. This supports essential tasks such as preprocessing, subsetting, statistical computation, and conditional filtering. These principles extend to more advanced structures including matrices, lists, and data frames.


Summary

R’s 1‑based indexing provides structured control over vector elements. Whether accessing single values, sequences, or modifying elements conditionally, indexing serves as a foundational technique for effective data handling and analysis.

Leave a Comment

💬 Join Telegram