0
0
R Programmingprogramming~5 mins

Negative indexing for exclusion in R Programming

Choose your learning style9 modes available
Introduction
Negative indexing helps you remove items from a list or vector easily without changing the original order.
When you want to skip certain elements from a list while keeping the rest.
When you have a vector and want to exclude specific positions quickly.
When cleaning data by removing unwanted rows or columns in a table.
When you want to focus on all but a few elements in a sequence.
Syntax
R Programming
vector[-index]
vector[-c(index1, index2, ...)]
Use a minus sign before the index number to exclude that element.
You can exclude multiple elements by combining their indexes inside c().
Examples
This removes the second element (20) and returns the rest.
R Programming
x <- c(10, 20, 30, 40, 50)
x[-2]
This removes the first and last elements (10 and 50).
R Programming
x <- c(10, 20, 30, 40, 50)
x[-c(1, 5)]
Removes the third element ('c') from the character vector.
R Programming
x <- c('a', 'b', 'c', 'd')
x[-3]
Sample Program
We create a vector of numbers and remove the third element (15) using negative indexing.
R Programming
numbers <- c(5, 10, 15, 20, 25)
# Remove the 3rd element
result <- numbers[-3]
print(result)
OutputSuccess
Important Notes
Negative indexing does not change the original vector unless you assign the result back.
If you use an index that is out of range, R will ignore it without error.
You cannot mix positive and negative indexes in the same operation.
Summary
Negative indexing removes elements by position from vectors or lists.
Use a minus sign before the index or a vector of indexes to exclude multiple elements.
It is a simple way to skip unwanted items without deleting or modifying the original data.