Dates and Times – Simple and Easy with lubridate exercises (part 1)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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
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.