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
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.
The expression returns a vector.
In the following program, we take a vector in
x, and access its third element using index 3.
x <- c(5, 10, 15, 20, 25, 30) result <- x cat("Item : ", result)
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.
x <- c(5, 10, 15, 20, 25, 30) result <- x[c(2, 3, 5)] cat("Items : ", result)
Items : 10 15 25
In this R Tutorial, we learned how to access items of a vector using index notation, with the help of examples.