An Easy Ways to Work With Dates in R
Hello developers. Welcome to our new article. Today, I am going to talk about date type in R. Lots of people struggle to work with date types.
Date types is so vital especially for time series analysis and recent days I faced with several difficulties in time series while working with them. Therefore I decide to write an article to provide solutions to people’s concerns.
Let’s begin with difficulties that you may encounter in R.
How to Find Current Date in R?
In order to print current date in R type following command.
Sys.Date()
It is rather simple.
How to Find Current Date Time in R?
In order to find current date time in R type following command
Sys.time()
How to Convert character to Date?
Let’s consider we have the following vectors and we construct a data frame with them.
person <- c("Jack", "Rose", "Sam")
birthdates <- c("1999-03-01", "2000-12-23", "2000-09-20") # FORMAT: Year-Month-Day
people <- data.frame(name = person, birthdate = birthdates)
If we try to print type of the birthdates, character type will be shown on the terminal. We can fix that by using as.Date() function while constructing a data.frame as shown below.
people <- data.frame(name = person, birthdate = as.Date(birthdates))
After the execution of above code, birthdate type will be Date. This is a simple example, but in real scenario, probably you will read your data from a csv or excel files.
Let’s look at that situation as well.
As you can see on the image, we are going to read data from csv file. In order to read the file, execute the following line.
people <- read.csv("people.csv")
After reading from csv file, the type of the birthdate column is character. We are going to use as.Date() function one more time.
people$birthdate = as.Date(people$birthdate)
In above code, we convert from character to Date and store the result on the same column, and with this code, every birthdate value converted to Date type.
How to Convert Date Type to character?
The reverse process will be straightforward. We are going to use as.character() function to convert from Date to character.
people$birthdate = as.character(people$birthdate)
How to Convert Date Type into Specific Format?
Conversion from Date to character and character to Date is very simple and easy to understand. Now we are going to convert Date type into desired date format.
In our example, Date format is : Year — Month — Day which is equvivalent to %Y-%m-%d in R. In order to make this happen, format() function will be used. For instance, I want to convert our Date format into Day-Month-Year which is equvivalent to
%d-%m-%Y in R.
people$birthdate = format(people$birthdate, format="%d-%m-%Y")
Here’s the result of before after.
Date Formats in R
Here’s the list of common date formats.
In order to test them on your own, try the following code.
print(format(Sys.Date(), format="%d")) # prints '08'
print(format(Sys.Date(), format="%A")) # prints 'Sunday'
print(format(Sys.Date(), format="%B")) # prints 'January'
print(format(Sys.Date(), format="%Y")) # prints '2023'
print(format(Sys.Date(), format="%B - %Y")) # prints 'January - 2023'
Try every date format on your own in order to keep those well in your mind. Caution: printed values will be different in your machine, because I used Sys.Date() which is the current date.
Time Formats in R
Here’s the list of time formats in R
In order to practice time formats, examine them by yourself like the way I did below.
print(format(Sys.time(), format="%H")) # prints '00'
print(format(Sys.time(), format="%M")) # prints '19'
print(format(Sys.time(), format="%X")) # prints '12:19:44 AM'
print(format(Sys.time(), format="%Z")) # prints '+04'
Caution: printed values will be different in your machine, because I used Sys.time() which is the current date time in R.
How to Find Current Time in Different Cities?
We are already familiar to find current time in R. Let’s assume, you want to find current time in Paris or Berlin. The following code snippet will help you.
print(as.POSIXlt(Sys.time(), "Europe/Berlin"))
print(as.POSIXlt(Sys.time(), "Europe/Paris"))
This code snippet will give what you want. If you want to know time in different cities other than Paris or Berlin. Execute the following code snippets.
tab <- file.path(R.home("share"), "zoneinfo", "zone1970.tab")
Execute the following code snippet as well.
if(file.exists(tab)) {
cols <- c("code", "coordinates", "TZ", "comments")
tmp <- read.delim(file.path(R.home("share"), "zoneinfo", "zone1970.tab"),
header = FALSE, comment.char = "#", col.names = cols)
if(interactive()) View(tmp)
head(tmp, 10)
}
After executing latter code snippet, R studio will open a new tab includes different cities with date and time. If the code snippet isn’t work on your Windows machine, find the folder that you installed R programming language. Most of the times it will be on Program Files folder.
For example, in my machine the time zones file path given as below.
C:\Program Files\R\R-4.2.1\share\zoneinfo\zone1970.tab
If you can’t find the path on that location, please search the time zone in this file: Time zones in R. If you struggle to implement this on your own, please let me know on the comment section below.
How to Work with Lubridate library?
Working with base components is great, what’s better than that is you can install third party libraries to extend usability of the program. In R programming language there are tons of libraries that you can use to make your life easier. Lubridate is one of them that makes working with times and dates easier. Let’s look at a couple of examples.
Let’s assume you want to parse your dates with the format Year-Month-Date. In lubridate, you can use ymd() function. One of the advantages of this function is you can memorize it easily.
If you look at closely, you’ll realize the function name is the combination of firts letters of Year, Month, Date words.
ymd("03-01-22") # 2003-01-22
ymd("11-11-21") # 2011-11-21
ymd("95-12-23") # 1995-12-23
Furthermore, there are other functions like this one, such as dym(), dmy(), ydm() and so on.
dym() # day year month
dmy() # day month year
mdy() # month day year
myd() # month year day
ymd() # year month day
ydm() # year day month
In addition, you can also set hour, minute, second along with date.
ydm_h("99-23-12-14") # "1999-12-23 14:00:00 UTC"
ydm_hm("99-23-12-14-23") # "1999-12-23 14:23:00 UTC"
ydm_hms("99-23-12-14-23-34") # "1999-12-23 14:23:34 UTC"
Hour, minute, second options are availabe for the other ones as well, not for all of them, but a few of them includes those.
Lubridate provide us to set not only dates but also times with easy to memorize function names.
hm("14:23") # "14H 23M 0S", h - hour, m - minute
hms("15:33:59") # "15H 33M 59S", h - hour, m - minute, s - second
How to Find Difference Between Two Dates?
In my point of view, this question asked numerous time on Stackoverflow for each programming languages. Some of them mentioned on below.
- How to Find Difference Between Two Dates in Java?
- How to Find Difference Between Two Dates in C#?
- How to Find Difference Between Two Dates in Javascript?
- How to Find Difference Between Two Dates in PHP?
And many many more. You can find it on other programming languages as well, just google it. Let’s find an answer for this question in R programming language.
First define 2 dates and call whatever name you want. I called date1 and date2 for simplicity. The dates’ formats described as Year-Month-Date (%Y-%M-%d).
date1 <- as.Date("2023-01-21")
date2 <- as.Date("2023-01-24")
You can easily discern that there is a difference of 3 days between two dates. In R, you can find that by simply subtract the bigger date (date2) from smaller date (date1).
date2 - date1 # Time difference of 3 days
What if you want to know the difference in hours, minutes, seconds, weeks. In order to find it, difftime()
function can be useful. I changed the date2 time from 2023-01-24 to 2023-02-24 (1 month later) in order to see rational results.
date1 <- as.Date("2023-01-21")
date2 <- as.Date("2023-02-24")
difftime(date2, date1, units = "secs") # 2937600 secs
difftime(date2, date1, units = "mins") # 48960 mins
difftime(date2, date1, units = "hours") # 816 hours
difftime(date2, date1, units = "days") # 34 days
difftime(date2, date1, units = "weeks") # 4.857143 weeks
Conclusion
I hope you enjoyed the article and find it useful. Be lookout for more. By the way source code is available on Github.
Good bye and take care.