R/phone_it_in.R

Defines functions phone_it_in

Documented in phone_it_in

#' Easily clean up and standardize phone numbers
#'
#' This function takes phone numbers in multiple formats and makes them consistent.
#' @param phone A vector of numbers that are supposed to be phone numbers.
#' @param invalid A string that you want to assign to any numbers identified as invalid.
#' @return A vector of the same length as the input vector, reformatted.
#' @details Phone numbers can be either 7 or 10 digits and will be returned with that same number of digits.
#' @examples
#' x <- c("1234567", "123-4567.890", "1.23456", 1234567)
#' phone_it_in(x)
#' @export
phone_it_in <- function(phone, invalid = "") {
  phone <- gsub("[[:punct:]]", "", phone)          # remove punctuation
  phone <- gsub("\\s", "", phone)                           # remove whitespace
  phone[!nchar(phone) %in% c(7, 10)] <- invalid    # keep only 7 or 10 digit numbers
  phone[nchar(phone) == 7] <- gsub("(^\\d{3})(\\d{4}$)", "\\1-\\2", phone[nchar(phone) == 7])
  phone[nchar(phone) == 10] <- gsub("(^\\d{3})(\\d{3})(\\d{4}$)", "\\1-\\2-\\3", phone[nchar(phone) == 10])
  phone
}
Ingenuity-Inc/artlookR documentation built on May 18, 2022, 12:33 a.m.