Files
civilyticsR/R/utils.R
T

71 lines
1.6 KiB
R

#' Safe maximum
#' Take the max but ignore missing values
#'
#' @param x a numeric vector which may contain NA values
#'
#' @return the maximum non-missing value
#' @export
#'
#' @examples
#' safe_max(1:10)
#' safe_max(c(1:10, NA)) # 10
safe_max <- function(x) {
max(x, na.rm = TRUE)
}
#' Prettify proportion data
#' Make data expresed as proportions print out as prettily formatted characters with percentages
#'
#' @param x a numeric vector of proportions to convert to percentages
#' @param ndigit a vector of length 1 indicating the number of digits to display in the percent
#'
#' @return
#' @export
#'
#' @examples
#' pretty_per(0.2, ndigit = 1)
#' pretty_per(c(0.2, 0.332423, 0.4, 0.342342), ndigit = 2)
pretty_per <- function(x, ndigit = 1) {
x <- format(round(x, digits = 3) * 100, nsmall = ndigit)
x <- paste0(x, "%")
x[x == "NA%"] <- " - "
x <- trimws(x)
return(x)
}
options(knitr.kable.NA = "-")
#' Zero out missing values
#'
#' @param x a numeric vector with missing values
#'
#' @return a numeric vector with missing values replaced by 0
#' @export
#'
#' @examples
#' na_zero(1:10)
#' na_zero(c(NA, NA, 2:10))
na_zero <- function(x) {
x[is.na(x)] <- 0
return(x)
}
#' Prettify count data
#' Make integers propertly formatted as strings which include commas suitable for printing
#' @param x a numeric vector
#'
#' @return a character vector with commas introduced in place positions in the numbers
#' @export
#'
#' @examples
#' pretty_count(10)
#' pretty_count(1000)
#' pretty_count(1e8)
pretty_count <- function(x) {
x <- prettyNum(x, big.mark = ",")
return(x)
}