File: replace_nan_inf.R

package info (click to toggle)
r-cran-datawizard 1.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,300 kB
  • sloc: sh: 13; makefile: 2
file content (61 lines) | stat: -rw-r--r-- 1,411 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
59
60
61
#' @title Convert infinite or `NaN` values into `NA`
#' @name replace_nan_inf
#'
#' @description
#' Replaces all infinite (`Inf` and `-Inf`) or `NaN` values with `NA`.
#'
#' @param x A vector or a dataframe
#' @param ... Currently not used.
#'
#' @return
#' Data with `Inf`, `-Inf`, and `NaN` converted to `NA`.
#'
#' @examples
#' # a vector
#' x <- c(1, 2, NA, 3, NaN, 4, NA, 5, Inf, -Inf, 6, 7)
#' replace_nan_inf(x)
#'
#' # a data frame
#' df <- data.frame(
#'   x = c(1, NA, 5, Inf, 2, NA),
#'   y = c(3, NaN, 4, -Inf, 6, 7),
#'   stringsAsFactors = FALSE
#' )
#' replace_nan_inf(df)
#' @export

replace_nan_inf <- function(x, ...) {
  UseMethod("replace_nan_inf")
}

#' @export
replace_nan_inf.default <- function(x, ...) {
  x[is.nan(x) | is.infinite(x)] <- NA
  x
}

#' @inheritParams extract_column_names
#' @export
replace_nan_inf.data.frame <- function(x,
                                       select = NULL,
                                       exclude = NULL,
                                       ignore_case = FALSE,
                                       regex = FALSE,
                                       verbose = TRUE,
                                       ...) {
  # Select and deselect
  cols <- .select_nse(
    select,
    x,
    exclude = exclude,
    ignore_case,
    regex = regex,
    verbose = verbose
  )

  for (i in cols) {
    x[[i]] <- replace_nan_inf(x[[i]])
  }

  x
}