An R Introduction to Statistics

Vector Index

We retrieve values in a vector by declaring an index inside a single square bracket "[]" operator.

For example, the following shows how to retrieve a vector member. Since the vector index is 1-based, we use the index position 3 for retrieving the third member.

> s = c("aa", "bb", "cc", "dd", "ee") 
> s[3] 
[1] "cc"

Unlike other programming languages, the square bracket operator returns more than just individual members. In fact, the result of the square bracket operator is another vector, and s[3] is a vector slice containing a single member "cc".

Negative Index

If the index is negative, it would strip the member whose position has the same absolute value as the negative index. For example, the following creates a vector slice with the third member removed.

> s[-3] 
[1] "aa" "bb" "dd" "ee"

Out-of-Range Index

If an index is out-of-range, a missing value will be reported via the symbol NA.

> s[10] 
[1] NA