File: num_to_char.R

package info (click to toggle)
r-cran-jsonlite 1.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,340 kB
  • sloc: ansic: 3,792; sh: 9; makefile: 6
file content (40 lines) | stat: -rw-r--r-- 1,213 bytes parent folder | download | duplicates (6)
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
#' @useDynLib jsonlite R_num_to_char
num_to_char <- function(x, digits = NA, na_as_string = NA, use_signif = FALSE, always_decimal = FALSE){
  if(is.na(digits)) digits <- NA_integer_;
  stopifnot(is.numeric(x))
  stopifnot(is.numeric(digits))
  stopifnot(is.logical(na_as_string))
  .Call(R_num_to_char, x, digits, na_as_string, use_signif, always_decimal)
}

#' @useDynLib jsonlite R_integer64_to_char
integer64_to_char <- function(x, na_as_string = TRUE){
  .Call(R_integer64_to_char, x, na_as_string)
}

num_to_char_R <- function(x, digits = NA, na_as_string = NA){
  if(is.na(digits)) digits <- NA_integer_;
  stopifnot(is.numeric(x))
  stopifnot(is.numeric(digits))
  stopifnot(is.logical(na_as_string))
  if(!is.integer(x) && !is.null(digits) && !is.na(digits)){
    x <- round(x, digits)
  }

  #convert to strings
  tmp <- as.character(x)

  # in numeric variables, NA, NaN, Inf are replaced by character strings
  if (any(missings <- which(!is.finite(x)))) {
    if(is.na(na_as_string)){
      tmp[missings] <- NA_character_;
    } else if(na_as_string){
      tmp[missings] <- wrapinquotes(x[missings])
    } else {
      tmp[missings] <- "null"
    }
  }

  #returns a character vector
  return(tmp)
}