As in any programming language, handling date and time variables can be quite frustrating, since, for example, there is no one single format for dates, there are different time zones and there are issues such as daylight saving time.
Base R provides several packages for handling date and time variables, but they require mastering cumbersome syntax.
In order to solve all those issues and more, R package “lubridate” was created. This package on one hand has a very easy and intuitive syntax and on the other hand has functions that cover a wide range of issues related to dates and times.
In this first part in the series of lubridate exercises, the basic functionality of the package is covered.
As always, let’s start by downloading and installing the package:
install.packages("lubridate")
library(lubridate)
Answers to the exercises are available here.
If you have different solutions, feel free to post them.
Parsing Date-times
The ymd() series of functions are used to parse character strings into dates.
The letters y, m, and d correspond to the year, month, and day elements of a date-time.
Exercise 1
Populate a variable called “start_date” with a date representation of string “23012017”
Exercise 2
Use the lubridate function today
to print the current date
Exercise 3
Extract the year
part from the “start_date” variable created on exercise 1
Exercise 4
Extract the month
part from the “start_date” variable created on exercise 1
Exercise 5
Extract the day
part from the “start_date” variable created on exercise 1
Exercise 6
Set the month
in variable “start_date” to February
Exercise 7
Add 6 days
to variable “start_date”.
Did you notice what happened to the month value?
Exercise 8
Substract 3 months
from variable “start_date”
Exercise 9 (Advanced)
Populate a field called concatenated_dates with a vector of dates containing the following values:
“31.12.2015”, “01.01.2016”, “15.02.2016”
Exercise 10 (Advanced)
Calculate in a short and simple way the addition of 1 thru 10 days to “start_date” variable
Exercise 10:
start_date + days(1:10)
Oh, I didn’t see think the solution would be different till I saw this comment.
Hi Jack,
Thanks for your feedback.
You are right: the solution you suggested is simpler and straight forward.
However, I’m leaving the original solution just for people to see an example of multiplication done with days…
Best Regards,
Avi
Thanks for the article!