Subsetting vector in R

24

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.
• The`[` operator always returns an object of the same class as the original. It can be used to select multiple elements of an object
• The `[[` 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.
• The `\$` 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 `[` operator

Extracting single element

```> vowels<-c("a","e","i","o","u")
> vowels[1]            ## Extract the first element
[1] "a"
> x<-vowels[1]        ## Extract the first element as new variable x
> vowels[2]           ## Extract the second element
[1] "e"```

Extracting multiple-element

The `[` 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]
[1] "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)]
[1] "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
[1] 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
[1] "e" "i" "o" "u"```

In the next post let us see how to subset a matrix and list.

Previous articleMedia Management MCQ Questions and Answers Part – 4
Author and Assistant Professor in Finance, Ardent fan of Arsenal FC. Always believe "The only good is knowledge and the only evil is ignorance - Socrates"
Subscribe
Notify of