How to get a month from a date in R DataFrame columns?

In today’s tutorial we will learn how to create a new month column out of an existing date column in an R dataframe.

We’ll start by creating an R DataFrame object which we will use in this tutorial. Feel free to use the code in RStudio or other R editor you might be using

#R

dates <- seq(as.Date('02/01/2023', format = '%m/%d/%Y'), as.Date('02/06/2023' ,format = '%m/%d/%Y'),by='days')
language <- c ('Javascript', 'R', 'Java', 'Python', 'Java', 'R')
candidates <- c (139, 81, 151, 171, 146, 151)

#Initialize DataFrame
my_df <- data.frame (interview_date = dates, language = language, candidates = candidates)

RStudio will return the following output:

interview_datelanguagecandidates
12023-02-01Javascript139
22023-02-02R81
32023-02-03Java151
42023-02-04Python171
52023-02-05Java146
62023-02-06R151

Extract month number from datetime in R

We can use the base R package and to quickly derive the month number into a new column:

my_df$interview_month <- format(my_df$interview_date, '%m')

Get month number and name with lubridate

When possible, i prefer to use the lubridate package (as well as dplyr for data manipulation), which offers some handy features for dealing with date and times:

Installing Lubridate

Run the following command in RStudio to get lubridate installed in your R dev environment

install.packages("lubridate")

Calculate the month number

Extracting the month number is easy:

library(lubridate)
my_df$interview_month_lb <- month(my_df$interview_date)

Derive the month name with lubridate

Lubridate has the month.name function that allows to convert the month number to its name:

library(lubridate)
my_df$interview_month_name <- month.name[month(my_df$interview_date)]

Concatenate month and year

We can also join the month and year as shown below.

library(lubridate)
my_df$month_number_year <- paste(month(my_df$interview_date),year(my_df$interview_date), sep = "-")

To sum it all up, here’s our DataFrame:

print(my_df)

interview_
date
languagecandidatesinterview_
month_lb
interview_
month_name
month_
number_year
12023-02-01Javascript1392February2-2023
22023-02-02R812February2-2023
32023-02-03Java1512February2-2023
42023-02-04Python1712February2-2023
52023-02-05Java1462February2-2023
62023-02-06R1512February2-2023