📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Adding and Deleting Vector Element

In R, vectors have a fixed length, so we cannot modify (add or delete elements of) a vector directly, but there are different techniques to add and delete elements from a vector dynamically.

Adding Elements to a Vector

Since vectors in R have a fixed length, you cannot modify them in-place, but you can create a new vector with additional elements.

Adding Elements at the Beginning

Example:

> vec_num <- c(10, 20, 30, 40, 50)
> vec_num <- c(5, vec_num)  # Add 5 at the beginning
> print(vec_num)            # Output: 5 10 20 30 40 50

Adding Elements at the End

Example:

> vec_num <- c(10, 20, 30, 40, 50)
> vec_num <- c(vec_num, 60, 70)  # Appends 60 and 70
> print(vec_num)                 # Output: 10 20 30 40 50 60 70

Inserting Elements at a Specific Position

The append() function inserts the given values after the position given in the after argument.

Example:

> vec_num <- c(10, 20, 30, 40, 50)
> vec_num <- append(vec_num, values = 25, after = 2)
> print(vec_num)  # Output: 10 20 25 30 40 50

Deleting Elements from a Vector

R does not provide direct deletion functions, but you can remove elements by creating a new vector without them.

Removing by Index

Example:

> vec <- c(10, 20, 30, 40, 50)
> vec <- vec[-3]  # Removes the element at index 3
> print(vec)      # Output: 10 20 40 50

Removing Multiple Elements by Index

Example:

> vec <- c(10, 20, 30, 40, 50)
> vec <- vec[-c(2, 4)]  # Removes the elements at positions 2 and 4
> print(vec)           # Output: 10 30 50

Removing Elements by Value

Example:

> vec <- c(10, 20, 30, 40, 50)
> vec <- vec[vec != 30]  # Removes the value 30
> print(vec)            # Output: 10 20 40 50

Here is the summary of various methods for adding and deleting elements from vectors.

Operation Method
Add elements at the beginning v <- c(new_values, v)
Add elements at the end v <- c(v, new_values)
Insert elements at a position v <- append(v, values, after = index)
Remove element by index v <- v[-index]
Remove multiple elements v <- v[-c(index1, index2)]
Remove element by value v <- v[v != value]