which() in basic

This is a pretty usefull function to quickly establish which value/s meet/s a condition/s

Create a long vector of 100 random numbers from a standard normal distribution (mean = 0 and sd = 1). Use rnorm() to do it efficiently and elegantly. For convenience, round the numbers to 8 decimal points - use round() for that purpose. As often, before doing anything set.seed() to get the same output as here:

set.seed(666)
x <- round(rnorm(100),8) 

Quick look at the vector:

x
##   [1]  0.75331105  2.01435467 -0.35513446  2.02816784 -2.21687445
##   [6]  0.75839618 -1.30618526 -0.80251957 -1.79224083 -0.04203245
##  [11]  2.15004262 -1.77023084  0.86465359 -1.72015590  0.13412567
##  [16] -0.07582656  0.85830054  0.34490035 -0.58245269  0.78617038
##  [21] -0.69209929 -1.18304354  1.26885071 -0.31255155  0.03057126
##  [26] -1.48227491 -1.12664844 -1.76384329 -1.06261908 -1.34299924
##  [31]  0.75499616 -0.64148890  1.43113233 -0.62455072  0.22899484
##  [36]  0.26318052  0.42921830 -1.48422012  0.18000837  2.06106034
##  [41]  0.72560162 -0.48873390 -0.48412126  1.84559359  0.51543421
##  [46] -1.11478738 -0.31014892  0.09143147  0.64431728  0.37483448
##  [51]  0.19752628  1.18170978 -0.70065464 -0.60668500 -0.50569185
##  [56] -0.82082351 -0.23612114 -0.76970360  0.71999436  1.27995052
##  [61] -0.99367984 -0.90608870 -1.31823036  1.93449431  0.67806259
##  [66] -0.40247585  0.18554389  0.39984459  1.64399544 -0.06214899
##  [71] -0.31641277 -0.14566499  0.70360718  0.19168524 -1.22787980
##  [76] -0.06594228 -0.78587667 -2.94319389 -0.62765927 -0.55316263
##  [81]  1.48961190  0.88763819 -0.32840035 -1.28334614 -0.01438467
##  [86]  1.00533794  0.40311285  1.43250808  0.13734114 -1.34150706
##  [91] -0.48698389 -0.89996146  0.32048085  0.31472992 -1.04079374
##  [96]  0.38544421  0.79755477 -0.55370181  0.17731321  0.04298504

A lot of numbers, some being larger then 1. Which are those?

which(x>1)
##  [1]  2  4 11 23 33 40 44 52 60 64 69 81 86 88

The second, forth, eleventh, etc… Cool, right?

And now, let’s say that, for some reason, you want to know what is exactly the position of 1.27995052.

which(x == 1.27995052)
## [1] 60

60th! You can double check, but R is always Right!