R Challenge #2: Graceful Coding
Don't let the user crash. It's rude.
There are plenty of well-written articles on defensive programming, so I'll avoid repeating what you may already know. In short, if an error happens, give your code a strategy to fix it. That's the point of this R Code Challenge.
R Challenge #2 : Recover gracefully when an import fails
This challenge gives you the task of importing a CSV file from a web site. If the import fails, your code should load a local copy of the file. Easy if you know how...
Here's the video explaining the challenge - and showing a solution. (hint: try catch() )
Here's My Solution
This is the code I suggest - a deeper explanation is in the video above.
worldPopURL <- "https://population.un.org/wpp/Download/Files/1_Indicators%20(Standard)/CSV_FILES/WPP2019_TotalPopulationBySex.csv"
worldPopFile <- "worldPopulation.csv"
worldPopColClasses <- c("integer","character","integer",?
? ? ? ? ? ? ? ? ? ? ? ? "factor", "integer", "numeric",
? ? ? ? ? ? ? ? ? ? ? ? "numeric","numeric","numeric","numeric")?
worldPop <- tryCatch(read.csv(worldPopURL,colClasses = worldPopColClasses ),
? ? ? ? ? ? ? ? ? ? ?error = function(e) {
? ? ? ? ? ? ? ? ? ? ? ?message(paste("The error is:", e))
? ? ? ? ? ? ? ? ? ? ? ?read.csv(worldPopFile,colClasses = worldPopColClasses )
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?)
领英推荐
More about tryCatch()
I did a video on try catch for the R weekly series. It's a powerful tool and has a lot of options you might not realize are there. Take a look...
The Hidden Story
Good sample data should be interesting and easy to obtain. Unfortunately, the internet is chaotic and data is short-lived. Data disappears, it gets updated, it gets moved. The data set I use in this series of code challenges seems stable - but every once in a while, it would go awol.
In the original code clinic, I used a public data set from the US Navy at Lake Pend Oreille. They provided a detailed list of the weather conditions on the lake - until they suddenly didn't. I was surprised at the number of people trying to complete the exercise and having no way to continue. We finally posted an incomplete set on GitHub.
I learned my lesson - and this is the challenge I pass on through this exercise: don't let the user fail!
How about you??
In this and future articles, I'll share some backstory behind each R challenge in this course. My peers have supplied other code challenges you might find interesting:?Javascript?...?Python?...?Java?...?Github?...?HTML?...?SQL?...?SQL for Data Science?...?PHP
Do you have some opinions on this challenge? Please share them in the comments below.
mnr