Public-Health-Scotland / phsmethods

An R package to standardise methods used in Public Health Scotland (https://public-health-scotland.github.io/phsmethods/)
https://public-health-scotland.github.io/phsmethods/
54 stars 13 forks source link

Formatting numbers as percentages (function) #61

Closed Nic-Chr closed 7 months ago

Nic-Chr commented 3 years ago

Opening this issue to suggest adding a function to format numbers as percentages.

format_perc <- function(x, digits = 1, nsmall = 1, round_half_up = TRUE, ...){
  if (round_half_up) {
    x <- janitor::round_half_up(x * 100, digits = digits)
    if (nsmall < digits) {
      y <- paste0(formatC(janitor::round_half_up(x, digits = nsmall), digits = nsmall, format = "f", ...), "%")
    } else {
      y <- paste0(formatC(x, digits = nsmall, format = "f", ...), "%")
    }
  } else {
    y <- paste0(formatC(round(x * 100, digits = digits), digits = nsmall, format = "f", ...), "%")
  }
  ifelse(grepl("NA", y, fixed = TRUE), NA_character_, y)
}

This uses janitor's round_half_up() by default with an argument to disable this behaviour.

Nic-Chr commented 7 months ago

Closing in favour of issue #127.