File: convertInteger.R

package info (click to toggle)
r-cran-bbmisc 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,256 kB
  • sloc: ansic: 176; sh: 9; makefile: 5
file content (58 lines) | stat: -rw-r--r-- 1,555 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#' @title Conversion for single integer
#'
#' @description
#' Convert single numeric to integer only if the numeric represents a single integer,
#' e.g. 1 to 1L.
#' Otherwise the argument is returned unchanged.
#'
#' @param x [any]\cr
#'   Argument.
#' @return Either a single integer if conversion was done or \code{x} unchanged.
#' @export
#' @examples
#' str(convertInteger(1.0))
#' str(convertInteger(1.3))
#' str(convertInteger(c(1.0, 2.0)))
#' str(convertInteger("foo"))
convertInteger = function(x) {
  if (is.integer(x) || length(x) != 1L)
    return(x)
  if (is.na(x))
    return(as.integer(x))
  if (is.numeric(x)) {
    xi = as.integer(x)
    if (isTRUE(all.equal(x, xi)))
      return(xi)
  }
  return(x)
}

#' @title Conversion for integer vector
#'
#' @description
#' Convert numeric vector to integer vector if the numeric vector fully represents
#' an integer vector,
#' e.g. \code{c(1, 5)} to \code{c(1L, 5L)}.
#' Otherwise the argument is returned unchanged.
#'
#' @param x [any]\cr
#'   Argument.
#' @return Either an integer vector if conversion was done or \code{x} unchanged.
#' @export
#' @examples
#' str(convertIntegers(1.0))
#' str(convertIntegers(1.3))
#' str(convertIntegers(c(1.0, 2.0)))
#' str(convertIntegers("foo"))
convertIntegers = function(x) {
  if (is.integer(x))
    return(x)
  if (length(x) == 0L || (is.atomic(x) && all(is.na(x))))
    return(as.integer(x))
  if (is.numeric(x)) {
    xi = as.integer(x)
    if (isTRUE(all.equal(x, xi, check.names = FALSE)))
      return(setNames(xi, names(x)))
  }
  return(x)
}