Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last digits from numbers which exceed a certain length

Tags:

r

maxlength

gsub

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))
like image 847
Valerie Avatar asked Dec 15 '22 05:12

Valerie


1 Answers

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
> 
like image 78
Ramesh K Avatar answered May 17 '23 16:05

Ramesh K