Subsetting Vectors

The way you tell R that you want to select some particular elements (i.e. a 'subset') from a vector | is by placing an 'index vector' in square brackets immediately following the name of the vector.

Index vectors come in four different flavors -- logical vectors, vectors of positive integers, | vectors of negative integers, and vectors of character strings -- each of which we'll cover in this.

lesson.
x <- c( -2.14976472, -0.05860281, NA,NA, -0.30042357,  0.97797872, -1.57337945,  0.14209524, -0.42439809,          NA)
x
##  [1] -2.14976472 -0.05860281          NA          NA -0.30042357  0.97797872
##  [7] -1.57337945  0.14209524 -0.42439809          NA
x[is.na(x)]
## [1] NA NA NA
y <- x[!is.na(x)]
y
## [1] -2.14976472 -0.05860281 -0.30042357  0.97797872 -1.57337945  0.14209524
## [7] -0.42439809

Recall that the expression y > 0 will give us a vector of logical values the same length as y, with | TRUEs corresponding to values of y that are greater than zero and FALSEs corresponding to values of y that are less than or equal to zero.

y>0
## [1] FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE
y[y>0]
## [1] 0.9779787 0.1420952
# Get positive elements of x that exclude NA
x[!is.na(x) & x >0]
## [1] 0.9779787 0.1420952
#how we'd subset the 3rd, 5th, and 7th elements of x
x[c(3,5,7)]
## [1]         NA -0.3004236 -1.5733795
#What if we're interested in all elements of x EXCEPT the 2nd and 10th?
x[c(-2,-10)]
## [1] -2.1497647         NA         NA -0.3004236  0.9779787 -1.5733795  0.1420952
## [8] -0.4243981
x[-c(2,10)]
## [1] -2.1497647         NA         NA -0.3004236  0.9779787 -1.5733795  0.1420952
## [8] -0.4243981

'named' elements.

vect <- c(foo=11, bar=2, norf=NA)
vect
##  foo  bar norf 
##   11    2   NA
#We can also get the names of vect by passing vect as an argument to the names() function.
names(vect)
## [1] "foo"  "bar"  "norf"
#Alternatively, we can create an unnamed vector vect2 with c(11, 2, NA)
#| Then, we can add the `names` attribute to vect2 after the fact with names(vect2) <- c("foo", "bar",| "norf")

vect2 <- c(11,2,NA)
names(vect2) <- c("foo", "bar", "norf")

#check that vect and vect2 are the same by passing them as arguments to the identical()
# function.
identical(vect,vect2)
## [1] TRUE

subsetting a vector by named elements

Get the second element of vect.

vect["bar"]
## bar 
##   2
#Likewise, we can specify a vector of names with vect[c("foo", "bar")]. Try it out.
vect[c("foo","bar")]
## foo bar 
##  11   2