knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
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"
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". We can retrieve multiple elements by using a index that is itself a vector:
> s = c("aa", "bb", "cc", "dd", "ee") > s[3:5] [1] "cc" "dd" "ee"
or retrieve the first, third and fifth elements:
> s = c("aa", "bb", "cc", "dd", "ee") > s[c(1,3,5)] [1] "aa" "cc" "ee"
If an index is out-of-range, a missing value will be reported via the symbol NA.
> s[10] [1] NA
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"
Multiple elements can also be removed this way. Say we wanted to remove the first, second and third elements:
> s[-1:-3] [1] "dd" "ee"
Alternatively, vectors of logical values can also be used for indexing. Retrieving the first, third and fifth elements can be done by:
ix <- c(TRUE, FALSE, TRUE, FALSE, TRUE) > s[ix] [1] "aa" "cc" "ee"
Logical vectors can be easily generated. Say we have a vector of ten uniform random variates:
x <- runif(10)
A vector of logical values which identify the values of 'x' which are larger than 0.5 can be generated thus:
x > 0.5
which is a ten-element logical vector. This vector can be used as an index vector:
x[x > 0.5]
The 'which' function can be used to convert from a logical index vector to an integer index vector.
which(x > 0.5)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.