Description Usage Arguments Value Acknowledgements Note Author(s) Examples
Returns the index of a vector which contains the value closest to an arbitary value
1 |
x |
vector of values |
xval |
value to find the nearest value in |
outside |
if not set to |
na.rm |
NA behaviour: |
returns an integer:
index |
the index of |
Written in collaboration with A.M.Pollard <mark.pollard@rlaha.ox.ac.uk> with the financial support of the Natural Environment Research Council (NERC) grant GR3/11395
The vector doesn't have to be in any particular order - this routine will just give the index of the nearest number. The only inconsistancy is that if the value of xval
are not strictly within the range of the vector the function will return an error. To prevent this call with the outside=TRUE
flag enabled. If there are many values which match the 'nearest' value then the function will return a vector of their indicies.
David Lucy <d.lucy@lancaster.ac.uk> http://www.maths.lancs.ac.uk/~lucy/
Robert Aykroyd <r.g.aykroyd@leeds.ac.uk>http://www.amsta.leeds.ac.uk/~robert/
1 2 3 4 5 6 7 8 9 10 11 12 | # make up a vector
x <- c(1,2,2,2,2,2,3,4,5,6,7,8,9,10)
# conventional useage - xval within range should return 9
nearest(x, 4.7)
# xval - outside the range of x should return 14
nearest(x, 12.7, outside=TRUE)
# many 'nearest' values in x - should return - 2 3 4 5 6
nearest(x, 1.7)
# make x[3] an NA
x[3] <- NA
# returns - 2 4 5 6 - by enabling na.rm
nearest(x, 1.7, na.rm=TRUE)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.