Access Items of R Vector 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

Access Single Item using Index

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

Access Multiple Items using Indices

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

Index Out of Range

If we try to access element outside the index range, we get the value of element as NA.

example.R

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

Output

Items :  NA

Since there are only six elements in the vector x, index 8 would be out of range, therefore NA in the result.

ADVERTISEMENT

Conclusion

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