Statistical Analysis: an Introduction using R/R/Accessing elements of vectors

It is common to want to access certain elements of a vector: for example, we might want to use only the 10th element, or the first 4 elements, or select elements depending on their value. The way to do this is to take the vector and prepend the indexing operator, [] (i.e. square brackets). If these square brackets contain

A positive number or numbers, then this has the effect of picking those particular elements of the vector

A negative number or numbers, then this has the effect of picking the whole vector except those elements

A logical vector, then each element of the logical vector indicates whether to pick (if TRUE) or not (if FALSE) the equivalent element of the original vector[1].

The use of logical vectors may seem a little complicated. However, they can be extremely useful, because they are the key behind using comparison operators. These can be used, for example, to identify which US states are small, with an area less than (<) 10 000 square miles (as demonstrated below).

Input:

1 min(state.area) #This gives the area of the smallest US state...
2 which.min(state.area) #... this shows which element it is (the 39th as it happens)
3 state.name[39] #You can obtain individual elements by using square brackets
4 state.name[39] <- "THE SMALLEST STATE" #You can replace elements using [] too
5 state.name #The 39th name ("Rhode Island") should now have been changed
6 state.name[1:10] #This returns a new vector consisting of only the first 10 states
7 state.name[-(1:10)] #Using negative numbers gives everything but the first 10 states
8 state.name[c(1,2,2,1)] #You can also obtain the same element multiple times
9 ###Logical vectors are a little more complicated to get your head round
10 state.area < 10000 #A LOGICAL vector, identifying which states are small
11 state.name[state.area < 10000] #So this can be used to select the names of the small states

Although the [] operator can be used to access just a single element of a vector, it is particularly useful for accessing a number of elements at once. Another operator, the double square-bracket ([[) exists for specifically accessing a single element. While not particularly useful for vectors, it comes into its own for #Lists and #Data frames.