In R you can subset various objects such as Vector, Matrix and List.
There are three operators that can be used to extract subsets of R objects.
[ operator always returns an object of the same class as the original. It can be used to select multiple elements of an object
[[ operator is used to extract elements of a list or a data frame. It can only be used to extract a single element and the class of the returned object will not necessarily be a list or data frame.
$ operator is used to extract elements of a list or data frame by literal name. Its semantics are similar to that of
Subsetting a Vector
Vectors are basic objects in R and they can be subsetted using the
Extracting single element
> vowels<-c("a","e","i","o","u") > vowels ## Extract the first element  "a" > x<-vowels ## Extract the first element as new variable x > vowels ## Extract the second element  "e"
[ operator can be used to extract multiple elements of a vector bypassing the operator an integer
sequence. Here we extract the first four elements of the vector.
> vowels[1:4]  "a" "e" "i" "o" > x<-vowels[1:4]
The sequence does not have to be in order; you can specify any arbitrary integer vector.
vowels[c(1, 3, 4)]  "a" "i" "o" > x<-vowels[c(1, 3, 4)]
We can also pass a logical sequence to the
[ operator to extract elements of a vector that satisfy a given condition. For example, here we want the elements of
vowels that come lexicographically after the letter “a”.
vowels<-c("a","e","i","o","u") > l<-vowels > "a" > l  FALSE TRUE TRUE TRUE TRUE
Another, more compact, way to do this would be to skip the creation of a logical vector and just subset the vector directly with the logical expression.
vowels1<-vowels[vowels > "a"] > vowels1  "e" "i" "o" "u"
In the next post let us see how to subset a matrix and list.