How to Format Date Objects in R (3 Examples)

In this article, I’ll illustrate how to modify the structure of date objects in R.

Constructing Example Data

x <- as.Date(c("2021-03-20", "2017-06-17", "2023-11-04"))  # Create example date
x                                                          # Print example date
# "2021-03-20" "2017-06-17" "2023-11-04"

Example 1: Showing Name of Months Instead of Numbers

format(x, "%Y-%h-%d")                                      # Using format() function
# "2021-Mrz-20" "2017-Jun-17" "2023-Nov-04"

Example 2: Changing Order of Years, Months & Days

format(x, "%d-%m-%Y")                                      # Using format() function
# "20-03-2021" "17-06-2017" "04-11-2023"

Example 3: Appending Hours, Minutes & Seconds to Date Object

format(x, "%Y-%m-%d-%H-%M-%S")                             # Using format() function
# "2021-03-20-00-00-00" "2017-06-17-00-00-00" "2023-11-04-00-00-00"

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top