Addresses within Vectors
There are two important functions for finding addresses within arrays. The function which is very easy to understand. The vector y (see above) looks like this:
y
[1] 8 3 5 7 6 6 8 9 2 3 9 4 10 4 11
Suppose we wanted to know which elements of y contained values bigger than 5. We type
which(y>5)
[1] 1 4 5 6 7 8 11 13 15
Notice that the answer to this enquiry is a set of subscripts. We don't use subscripts inside the which function itself. The function is applied to the whole array. To see the values of y that are larger than 5, we just type
y[y>5]
[1] 8 7 6 6 8 9 9 10 11
Note that this is a shorter vector than y itself, because values of 5 or less have been left out:
length(y) [1] 15 length(y[y>5]) [1] 9
To extract every nth element from a long vector we can use seq as an index. In this case I want every 25th value in a 1000-long vector of normal random numbers with mean value 100 and standard deviation 10:
xv<-rnorm(1000,100,10) xv[seq(25,length(xv),25)] [1] 100.98176 91.69614 116.69185 97.89538 108.48568 100.32891 94.46233 [8] 118.05943 92.41213 100.01887 112.41775 106.14260 93.79951 105.74173 [15] 102.84938 88.56408 114.52787 87.64789 112.71475 106.89868 109.80862 [22] 93.20438 96.31240 85.96460 105.77331 97.54514 92.01761 97.78516 [29] 87.90883 96.72253 94.86647 90.87149 80.01337 97.98327 92.77398 [36] 121.47810 92.40182 87.65205 115.80945 87.60231
Get The R Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.