An R Introduction to Statistics

Numeric Index Vector

A new vector can be sliced from a given vector with a numeric index vector, which consists of member positions of the original vector to be retrieved.

Here it shows how to retrieve a vector slice containing the second and third members of a given vector s.

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

Duplicate Indexes

The index vector allows duplicate values. Hence the following retrieves a member twice in one operation.

> s[c(2, 3, 3)] 
[1] "bb" "cc" "cc"

Out-of-Order Indexes

The index vector can even be out-of-order. Here is a vector slice with the order of first and second members reversed.

> s[c(2, 1, 3)] 
[1] "bb" "aa" "cc"

Range Index

To produce a vector slice between two indexes, we can use the colon operator ":". This can be convenient for situations involving large vectors.

> s[2:4] 
[1] "bb" "cc" "dd"

More information for the colon operator is available in the R documentation.

> help(":")