How to convert a Datetime to day of week in R dataframes?

When data wrangling, we are often in need of deriving different date formats our of datetime objects in our DataFrame.

In this tutorial we will learn how how we can add new columns containing the the week day number and name out our a date column in our DataFrame.

Create Example DataFrame

First we will define a very simple DataFrame that you can use in order to follow along with this example:

library(lubridate)

stamps <- seq (ymd_hms ('2024-04-02 13:00:00'), ymd_hms ('2024-04-06 13:00:00'), by ='days')

# define vectors
language <- c ('Python', 'Java', 'Javascript', 'Javascript', 'Java')
salary <- c (139.0, 97.0, 135.0, 99.0, 157.0)

# create DataFrame
hiring <- data.frame (dates = stamps, language = language, salary = salary)

print(hiring)

Note: we used the lubridate package and its ymd function to create the datetime objects for our DataFrame.

Here are our DataFrame rows:

dateslanguagesalary
12024-04-02 13:00:00Python139
22024-04-03 13:00:00Java97
32024-04-04 13:00:00Javascript135
42024-04-05 13:00:00Javascript99
52024-04-06 13:00:00Java157

Convert date column to day of week name

We can use the date formatter strftime as following in order to create a weekday_name column:

hiring$weekday_name <- strftime(hiring$date, '%A')
print (hiring$weekday_name)

Here’s our output:

[1] "Tuesday"   "Wednesday" "Thursday"  "Friday"    "Saturday" 

We can accomplish the same result by using the R weekdays function:

hiring$weekday_name <- weekdays(hiring$date)

Get the week day number from a date

Another possible case is to convert a date to a week day number. Here’s a short snippet using the lubridate package wday function:

library(lubridate)
hiring$weekday_num <- wday(hiring$date)
print (hiring$weekday_num)

Here’s our output – consisting of the day numbers.

[1] 3 4 5 6 7

Concatenating week day and number

Here’s a snippet that using the paste function joins the weekday number and date:

hiring$week_num_day_name <- paste("W", week(hiring$date), weekdays(hiring$date), sep = "-")
print (hiring$week_num_day_name)

This returns:

 "W-14-Tuesday"   "W-14-Wednesday" "W-14-Thursday"  "W-14-Friday"    "W-14-Saturday"