Table of Contents
The Complete Guide to Date Formats in R is a comprehensive reference guide to assist users with manipulating and formatting data in R. It covers topics such as the various date formats available in R, how to convert between date formats, and how to perform calculations with dates. This guide is designed to be a helpful resource for users of all experience levels.
The following table shows a variety of symbols that you can use to format dates in R:
Symbol | Definition | Example |
---|---|---|
%d | Day as a number | 19 |
%a | Abbreviated weekday | Sun |
%A | Unabbreviated weekday | Sunday |
%m | Month as a number | 04 |
%b | Abbreviated month | Feb |
%B | Unabbreviated month | February |
%y | 2-digit year | 14 |
%Y | 4-digit year | 2014 |
The following examples show how to use each of these formats in practice.
Example 1: Format Date with Day, Month, Year
The following code shows how to format a date using a month/day/year format:
#define date date <- as.Date("2021-01-25") #format date formatted_date <- format(date, format="%m/%d/%y") #display formatted date formatted_date [1] "01/25/21"
Note that we can use whatever separators we’d like in between each value.
For example, we could use dashes instead:
#define date date <- as.Date("2021-01-25") #format date formatted_date <- format(date, format="%m-%d-%y") #display formatted date formatted_date [1] "01-25-21"
Example 2: Format Date as Weekday
The following code shows how to format a date using a weekday format:
#define date date <- as.Date("2021-01-25") #format date as abbreviated weekday format(date, format="%a") [1] "Mon" #format date as unabbreviated weekday format(date, format="%A") [1] "Monday"
Example 3: Format Date as Month
The following code shows how to format a date as a month:
#define date date <- as.Date("2021-01-25") #format date as abbreviated month format(date, format="%b") [1] "Jan" #format date as unabbreviated month format(date, format="%B") [1] "January"
We can also format the date as a month and a day:
#define date date <- as.Date("2021-01-25") #format date as abbreviated month format(date, format="%b %d") [1] "Jan 25"
The following tutorials explain how to perform other common operations involving dates in R: