5) Selecting and Filtering from a numeric Vector.

This Blog entry is from the Data Structures section in Learn R.

There are a number of ways to specifically extract data from a vector, a process sometimes called subscripting.  In this Blog entry, the vector created beforehand will be used.  The simplest way to extract data from a vector is to specify the position inside square brackets.  To subscript and retrieve the third value in the vector type:

SequenceBasic[3]

selecting-a-variable-from-a-vector-in-r.png

Run the line of script to console:

variable-selected-from-a-vector-written-to-r.png

It can be observed that the value at the third position in the SequenceBasic vector has been returned.  Alternatively, specifying a negative value of 3 would return everything except the third position:

excluding-a-variable-from-the-return-of-a-vector-in-r.png

Run the line of script to console:

a-vector-returned-to-the-r-console-excluding-value.png

It can be observed that the third position of the vector has been excluded in the output.

Far more powerful is the ability to select from vectors based upon a logical statement, such as all values > 5:

SequenceBasic[SequenceBasic > 5]
returning-only-variables-that-are-greater-in-vector-in-r.png

Run the line of script to console:

only-variables-that-are-greater-than-a-value-returned-in-r-console.png

It can be seen that only values greater than five have been returned.  The notion of selecting from a vector based on logical conditions further introduces operators:

·         & And.

·         | Or.

·         ! Not.

To create more discriminating selection from a vector, where the value must be > 2 and less than 5, type:

SequenceBasic[SequenceBasic > 2 & SequenceBasic <5]
vector-filtering-using-and-logic-script-in-r.png

Run the line of script to the console:

logical-filtering-returning-variables-from-vector-written-to-r-console.png

It can be seen that only the two values between 2 and 5 have been returned.