Extract Day from Date in R (Example)

 

This post explains how to return only the day of a Date object in R programming.

Table of contents:

Let’s take a look at some R codes in action…

 

Creation of Exemplifying Data

As first step, we have to construct some data that we can use in the example code below:

x <- "2022-10-17"                                 # Create example date
x                                                 # Print example date
# "2022-10-17"

The previous output of the RStudio console shows that our example data object contains a character string showing a date (i.e. the 17th of October 2022).

 

Example: Extracting Day from Date Object Using format() Function

This example explains how to extract the day of a date in R. First, we have to apply the as.Date function to format our input character string to a Date object:

x_formatted <- as.Date(x, format = "%Y-%m-%d")    # Convert character to date
x_formatted                                       # Print Date object
# "2022-10-17"

As you can see, the output looks exactly the same as our input character string. However, the class is different:

class(x_formatted)                                # Check class
# "Date"

Our updated data has the class “Date”.

Now, we can apply the format command to return only the day of our Date object:

x_day <- format(x_formatted, format = "%d")       # Extract day from date
x_day                                             # Print day
# "17"

The day of our Date object is 17.

 

Video & Further Resources

Would you like to know more about dates in R? Then I can recommend to have a look at the following video of my YouTube channel. I’m explaining the R syntax of this tutorial in the video.

 

The YouTube video will be added soon.

 

Furthermore, you may want to have a look at the related tutorials of this homepage. A selection of articles is shown below.

 

In this tutorial you learned how to get the day of a vector of dates in the R programming language. Let me know in the comments section, if you have additional questions. Furthermore, please subscribe to my email newsletter in order to get updates on the newest articles.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top