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

Make chi_pad() more strict #34

Closed jackhannah95 closed 4 years ago

jackhannah95 commented 4 years ago

Hi guys!

Just because I've left PHS, it doesn't mean you're shot of me :eyes: I'm still working with health data and still using phsmethods.

At the moment chi_pad() adds a leading zero to any nine digit character string:

phsmethods::chi_pad(c("123456789", "abcdefghi", "23"))
#> [1] "0123456789" "0abcdefghi" "23"

I'd like to make it a little more strict, so that it only adds a leading zero to strings comprised of nine numeric digits:

chi_pad <- function(x) {

  if (!inherits(x, "character")) {
    stop("The input must be of character class")
  }

  # Add a leading zero to any string comprised of nine numeric digits
  ifelse(stringr::str_detect(x, "^[0-9]{9}$"),
         paste0("0", x),
         x)
}

chi_pad(c("123456789", "abcdefghi", "23"))
#> [1] "0123456789" "abcdefghi"  "23"

I can update the documentation and tests as well.

Thanks!