There are several helpful functions included in {lubridate}
to convert columns to dates. For instanceif the column you want to convert is of the form “2012-11-21”, then you would use the function ymd()
,for “year-month-day”. If, however the column is “2012-21-11”, then you would use ydm()
. There’sa few of these helper functions, and they can handle a lot of different formats for dates. In our case,having the name of the month instead of the number might seem quite problematic, but it turns outthat this is a case that {lubridate}
handles painfully:
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
Some dates failed to parse, for instance for Morocco. This is because these countries have severalindependence dates; this means that the string to convert looks like:
1 |
|
which obviously cannot be converted by {lubridate}
without further manipulation. I ignore these cases forsimplicity’s sake.
Let’s take a look at the data now:
1 |
|
1 |
|
As you can see, we now have a date column in the right format. We can now answer questions such asWhich countries gained independence before 1960? quite easily, by using the functions year()
,month()
and day()
. Let’s see which countries gained independence before 1960:
1 |
|
1 |
|
You guessed it, year()
extracts the year of the date column and converts it as a numeric so that we can workon it. This is the same for month()
or day()
. Let’s try to see if countries gained their independence onChristmas Eve:
1 |
|
1 |
|
Seems like Libya was the only one! You can also operate on dates. For instance, let’s compute the difference betweentwo dates, using the interval()
column:
1 |
|
1 |
|
The independent_since
column now contains an interval object that we can convert to years:
1 |
|
1 |
|
We can now see for how long the last country to gain independence has been independent.Because the data is not tidy (in some cases, an African country was colonized by two powers,see Libya), I will only focus on 4 European colonial powers: Belgium, France, Portugal and the United Kingdom:
1 |
|
1 |
|
{lubridate}
contains many more functions. If you often work with dates, duration or interval data, {lubridate}
is a package that you have to master.
Hope you enjoyed! If you found this blog post useful, you might want to followme on twitter for blog post updates andbuy me an espresso or paypal.me.