#' 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
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.