Learn R Programming

GenKern (version 1.2-60)

nearest: Index of a vector nearest in value to a supplied value

Description

Returns the index of a vector which contains the value closest to an arbitary value

Usage

nearest(x, xval, outside=FALSE, na.rm=FALSE)

Arguments

x
vector of values
xval
value to find the nearest value in x to
outside
if not set to TRUE the function returns an error if xval is outside the range of x - default FALSE
na.rm
NA behaviour: TRUE drops cases with NA's, FALSE stops function with a warning if NA's are detected: default=FALSE

Value

index
the index of x with the value nearest to xval

Acknowledgements

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

Examples

Run this code
# 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)

Run the code above in your browser using DataLab