R Vector – Access Items using Index

To access items of a vector in R programming, use index notation with square brackets as vector[index]. For index, we may provide a single value that specifies the position of the item, or we may provide a vector of positions.

The syntax to access items of a vector x at index is

x[index]

Please note that the index starts at 1 and increments by 1 for subsequent items till the end of the vector. The index of first element is 1, index of second element is 2, and so on.

Return Value

The expression returns a vector.

Examples

In the following program, we take a vector in x, and access its third element using index 3.

example.R

x <- c(5, 10, 15, 20, 25, 30)
result <- x[3]
cat("Item : ", result)

Output

Item :  15

Now, let us take a vector x and access multiple items at indices 2, 3, 5. We pass these indices as vector inside square brackets.

example.R

x <- c(5, 10, 15, 20, 25, 30)
result <- x[c(2, 3, 5)]
cat("Items : ", result)

Output

Items :  10 15 25

Conclusion

In this R Tutorial, we learned how to access items of a vector using index notation, with the help of examples.