File: utilities-resolution.R

package info (click to toggle)
r-cran-ggplot2 3.5.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 9,944 kB
  • sloc: sh: 15; makefile: 5
file content (37 lines) | stat: -rw-r--r-- 1,158 bytes parent folder | download
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
31
32
33
34
35
36
37
#' Compute the "resolution" of a numeric vector
#'
#' The resolution is the smallest non-zero distance between adjacent
#' values.  If there is only one unique value, then the resolution is defined
#' to be one. If x is an integer vector, then it is assumed to represent a
#' discrete variable, and the resolution is 1.
#'
#' @param x numeric vector
#' @param zero should a zero value be automatically included in the
#'   computation of resolution
#' @param discrete should vectors mapped with a discrete scale be treated as
#'   having a resolution of 1?
#' @export
#' @examples
#' resolution(1:10)
#' resolution((1:10) - 0.5)
#' resolution((1:10) - 0.5, FALSE)
#'
#' # Note the difference between numeric and integer vectors
#' resolution(c(2, 10, 20, 50))
#' resolution(c(2L, 10L, 20L, 50L))
resolution <- function(x, zero = TRUE, discrete = FALSE) {
  if (is.integer(x) || zero_range(range(x, na.rm = TRUE))) {
    return(1)
  }
  if (discrete && is_mapped_discrete(x)) {
    return(1)
  }

  x <- unique0(as.numeric(x))
  if (zero) {
    x <- unique0(c(0, x))
  }
  d <- diff(sort(x))
  tolerance <- sqrt(.Machine$double.eps)
  min(d[d > tolerance])
}