June 2007
Beginner to intermediate
950 pages
27h 8m
English
Finding the value in a vector that is closest to a specified value is straightforward using which. Here, we want to find the value of xv that is closest to 108.0:
which(abs(xv-108)==min(abs(xv-108)))
[1] 332
The closest value to 108.0 is in location 332. But just how close to 108.0 is this 332nd value? We use 332 as a subscript on xv to find this out
xv[332]
[1] 108.0076
Thus, we can write a function to return the closest value to a specified value (sv)
closest<-function(xv,sv){ xv[which(abs(xv-sv)==min(abs(xv-sv)))] }
and run it like this:
closest(xv,108)
[1] 108.0076
Read now
Unlock full access