closest: Find closest matches

Description Usage Arguments Value Examples

View source: R/closest.R

Description

For each element of from, find the the closest element of within.

Usage

1
2
3
closest(from, within, outside = TRUE)

which.closest(from, within, outside = TRUE)

Arguments

from

a numeric vector (or coercible as such); the values to be matched.

within

a vector of the same nature as from; the values to be matched against.

outside

logicial. When TRUE (the default) return the extremities for elements outside of the range [min(within),max(within)]. When FALSE return NA for such elements

Value

A vector of integers of the same length as from: for closest(), the value of the closest elements of within; for which.closest() the indexes of those values.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
set.seed(1)
to_match  <- round(runif(5, min=0, max=100), 1)
reference <- round(runif(10, min=20, max=80), 1)

# compare the vectors
to_match
reference

# get closest mactches, or their index
closest(to_match, within=reference)
which.closest(to_match, within=reference)

# verify graphically
plot(
  x=c(reference, to_match),
  y=c(rep(2, 10), rep(1, 5)), ylim=c(0, 3), yaxt="n",
  xlab="", ylab=""
)
axis(2, at=1:2, labels=c("to match", "reference"))
# join closest points
segments(
  x0=to_match, y0=1,
  x1=closest(from=to_match, within=reference), y1=2
)
# join closest points inside "within"
abline(v=range(reference), lty="22")
segments(
  x0=to_match, y0=1,
  x1=closest(from=to_match, within=reference, outside=FALSE), y1=2,
col="red")

jiho/castr documentation built on April 5, 2020, 2:12 p.m.