Reputation: 257
Is there any function or easy, fast way to convert US zipcodes into state names using R. For this we have zipstate()
function in SAS.
In R, I tried this as:
library(zipcode)
newzips = as.data.frame.factor(zipcode[,1])
for(i in 1:nrow(dmefzip)){
for(j in 1:nrow(zipcode)){
if(dmefzip[i,1]== (newzips[j,1]) ){
dmefzip[i,"state"] = zipcode[j,3]
break
}
}
}
It is working but as there are around 35000 rows in my data, it is taking hours. Please suggest some way. Thanks!
Upvotes: 1
Views: 398
Reputation: 2663
Oh dear that double loop is really inefficient. First of all for a single zip code it would be much faster to simply get the matching state by doing zipcode$state[zipcode$zip %in% YOURZIPCODEHERE]
for a whole bunch of zip codes using match
would serve your needs better.
dmefzip$state = zipcode$state[match(dmefzip[,1],zipcode$zip)]
Upvotes: 2