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:
Note: we used the lubridate package and its ymd function to create the datetime objects for our DataFrame.
Here are our DataFrame rows:
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:
 "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.
 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)
"W-14-Tuesday" "W-14-Wednesday" "W-14-Thursday" "W-14-Friday" "W-14-Saturday"