RObservations #13: Simulating FSAs in lieu of real postal code data.

[This article was first published on r – bensstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Introduction

Source: The Toronto Star

Often when scraping data, websites will ask a user to enter a postal code to get the locations near it. If you are interested in collecting data on locations in Canada for an entire Province or the entire province from a site, it might be hard to find a list of all postal codes or FSAs in Canada or in a given province which is easy to use. Information on how FSAs work can be found here.

In this blog, I’m going to share a brief snippet of code that you can use to generate Canadian FSAs. While some FSAs generated may not actually exist, if we follow the rules about Canadian postal codes, it serves as a good substitute in lieu of an actual list.

The Code

The code is essentially 3 nested for-loops. While many R users would not advise using for-loops, I find that for this case it is easier to understand and write.

# First make the list
fsa_list<-c()
# The numbers we are using
numbers <- c(0:9)
# The letters used for each province at the beginning of the FSA
province_alphabet<-c("A","B","C","E","G","H","J","K","L","M","N","P","R","S","T","V","X","Y")

# Letters not used in postal codes

nonLetters<- c("D", "F", "I", "O", "Q", "U")

second_letter<-LETTERS[!(LETTERS  %in% nonLetters)]

for(letter1 in province_alphabet){
  for(number in numbers){
    # Remove the letters we are not going to use
    for(letter2 in second_letter){
     # Inefficient, but it gets the job done
     fsa_list<-c(fsa_list,paste0(letter1,number,letter2)) 
    }
  }
}

We now have our simulated FSAs!

sample(fsa_list, 10)


##  [1] "J5T" "K4W" "E0L" "J8Z" "S9E" "T3E" "C9E" "Y0S" "X5N" "N6L"

Want to see more of my content?

Be sure to subscribe and never miss an update!

To leave a comment for the author, please follow the link and comment on their blog: r – bensstats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)