Atomic vectors (which excludes lists and expressions, which are also vectors) are subset using the [
operator:
# create an example vector
v1 <- c("a", "b", "c", "d")
# select the third element
v1[3]
## [1] "c"
The [
operator can also take a vector as the argument. For example, to select the first and third elements:
v1 <- c("a", "b", "c", "d")
v1[c(1, 3)]
## [1] "a" "c"
Some times we may require to omit a particular value from the vector. This can be achieved using a negative sign(-
) before the index of that value. For example, to omit to omit the first value from v1, use v1[-1]
. This can be extended to more than one value in a straight forward way. For example, v1[-c(1,3)]
.
> v1[-1]
[1] "b" "c" "d"
> v1[-c(1,3)]
[1] "b" "d"
On some occasions, we would like to know, especially, when the length of the vector is large, index of a particular value, if it exists:
> v1=="c"
[1] FALSE FALSE TRUE FALSE
> which(v1=="c")
[1] 3
If the atomic vector has names (a names
attribute), it can be subset using a character vector of names:
v <- 1:3
names(v) <- c("one", "two", "three")
v
## one two three
## 1 2 3
v["two"]
## two
## 2
The [[
operator can also be used to index atomic vectors, with differences in that it accepts a indexing vector with a length of one and strips any names present:
v[[c(1, 2)]]
## Error in v[[c(1, 2)]] :
## attempt to select more than one element in vectorIndex
v[["two"]]
## [1] 2
Vectors can also be subset using a logical vector. In contrast to subsetting with numeric and character vectors, the logical vector used to subset has to be equal to the length of the vector whose elements are extracted, so if a logical vector y
is used to subset x
, i.e. x[y]
, if length(y) < length(x)
then y
will be recycled to match length(x)
:
v[c(TRUE, FALSE, TRUE)]
## one three
## 1 3
v[c(FALSE, TRUE)] # recycled to 'c(FALSE, TRUE, FALSE)'
## two
## 2
v[TRUE] # recycled to 'c(TRUE, TRUE, TRUE)'
## one two three
## 1 2 3
v[FALSE] # handy to discard elements but save the vector's type and basic structure
## named integer(0)