0
0
R Programmingprogramming~5 mins

Vector indexing (1-based) in R Programming

Choose your learning style9 modes available
Introduction

Vector indexing lets you pick specific items from a list of values. In R, counting starts at 1, not 0.

You want to get the first or last item from a list of numbers.
You need to select multiple specific items from a list.
You want to change or check a particular item in a list.
You want to skip some items and only use certain ones.
You want to find items based on their position in the list.
Syntax
R Programming
vector[index]
vector[c(index1, index2, ...)]

Index numbers start at 1, not 0 like some other languages.

You can use a single number or a vector of numbers inside the square brackets.

Examples
Gets the first item from the vector v, which is 10.
R Programming
v <- c(10, 20, 30, 40)
v[1]
Gets the 2nd and 4th items from v, which are 20 and 40.
R Programming
v <- c(10, 20, 30, 40)
v[c(2, 4)]
Changes the 3rd item from 30 to 35, then shows the updated vector.
R Programming
v <- c(10, 20, 30, 40)
v[3] <- 35
v
Sample Program

This program shows how to get the first item, select multiple items, and change one item in a vector.

R Programming
numbers <- c(5, 10, 15, 20, 25)
first_item <- numbers[1]
selected_items <- numbers[c(2, 4)]
numbers[3] <- 18
print(first_item)
print(selected_items)
print(numbers)
OutputSuccess
Important Notes

Remember R starts counting at 1, so vector[1] is the first item.

If you use an index outside the vector length, R returns NA (missing value).

You can also use negative numbers to exclude items, like v[-1] to skip the first item.

Summary

Vector indexing in R starts at 1, not 0.

You use square brackets [] to pick or change items by position.

You can select one or many items by giving one or more index numbers.