Eliminate the leading '1' in front of US phone numbers in R

Viewed 333

I have a vector of US phone numbers, some of which have a leading "1" at the start of the phone number. If the number is 11 digits long, that means the first digit is the "1" I want to get rid of (at least within my data set).

phone <- c("1234567890", "1234567890", "5556456890", "5444567890", "19729772976")

I stripped all whitespace, punctuation, and dashes using

gsub("[- .)(+]|[a-zA-Z]*:?","", phone)

I am unsure how to code it to remove the first digit if the string is 11 characters long. Or in other words, remove the first character in a vector if the string is a certain length.

1 Answers

We can use sub from base R to match the 1 at the start (^) of the string, and capture the 10 digits (\\d{10}) as a group ((...)) till the end ($) of the string, and specify the backreference (\\1) of the captured group in replacement. This will prevent losing any 1 that are in the 10 digit strings

sub("^1(\\d{10})$", "\\1", phone)

-output

[1] "1234567890" "1234567890" "5556456890" "5444567890" "9729772976"
Related