I have a vector of zip codes that includes both five and nine digit codes. I want to drop the end digits from codes which exceed a length of five.
For example, the following codes:
zip<-c(11566, 46235, 50467, 856073217, 97333, 856159229)
should become
zip
11566
46235
50467
85607
97333
85615
I was thinking gsub would be a good way to fix this, but I can't figure out how to write the code for it. I tried this but it definitely doesn't work.
df$zip<- gsub("\\d(!i:5)", "", as.character(df$zip))
This should work
zip<-c(11566, 46235, 50467, 856073217, 97333, 856159229)
> s <- substr(zip,1,5)
> s
[1] "11566" "46235" "50467" "85607" "97333" "85615"
> as.numeric(s)
[1] 11566 46235 50467 85607 97333 85615
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With