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_date | language | candidates | |
---|---|---|---|
1 | 2023-02-01 | Javascript | 139 |
2 | 2023-02-02 | R | 81 |
3 | 2023-02-03 | Java | 151 |
4 | 2023-02-04 | Python | 171 |
5 | 2023-02-05 | Java | 146 |
6 | 2023-02-06 | R | 151 |
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 | language | candidates | interview_ month_lb | interview_ month_name | month_ number_year | |
---|---|---|---|---|---|---|
1 | 2023-02-01 | Javascript | 139 | 2 | February | 2-2023 |
2 | 2023-02-02 | R | 81 | 2 | February | 2-2023 |
3 | 2023-02-03 | Java | 151 | 2 | February | 2-2023 |
4 | 2023-02-04 | Python | 171 | 2 | February | 2-2023 |
5 | 2023-02-05 | Java | 146 | 2 | February | 2-2023 |
6 | 2023-02-06 | R | 151 | 2 | February | 2-2023 |