22.1 C
London
Wednesday, July 23, 2025
HomeStatistics TutorialRHow to Convert Factor to Date in R (With Examples)

How to Convert Factor to Date in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use one of the following two methods to quickly convert a factor to a date in R:

Method 1: Use Base R

as.Date(factor_variable, format = '%m/%d/%Y')

Method 2: Use Lubridate

library(lubridate)

mdy(factor_variable)

The following examples show how to use each method with the following data frame:

#create data frame
df frame(day=factor(c('1/1/2020', '1/13/2020', '1/15/2020')),
                 sales=c(145, 190, 223))

#view data frame
df

        day sales
1  1/1/2020   145
2 1/13/2020   190
3 1/15/2020   223

#view class of 'day' variable
class(df$day)

[1] "factor"

Example 1: Convert Factor to Date Using Base R

The following code shows how to convert the ‘day’ variable in the data frame from a factor to a date using the as.Date() function from base R:

#convert 'day' column to date format
df$day Date(df$day, format = '%m/%d/%Y')

#view updated data frame
df

         day sales
1 2020-01-01   145
2 2020-01-13   190
3 2020-01-15   223

#view class of 'day' variable
class(df$day)

[1] "Date"

Notice that the ‘day’ variable has been converted to a date format.

Example 2: Convert Factor to Date Using Lubridate

The following code shows how to convert the ‘day’ variable from a factor to a date using the mdy() function from the lubridate package:

library(lubridate)

#convert 'day' column to date format
df$day #view updated data frame
df

         day sales
1 2020-01-01   145
2 2020-01-13   190
3 2020-01-15   223

#view class of 'day' variable
class(df$day)

[1] "Date"

The ‘day’ variable has been converted to a date format.

Note that mdy() indicates a month-day-year format. 

Note: You can find the complete documentation for the lubridate package here.

Additional Resources

The following tutorials explain how to perform other common conversions in R:

How to Convert Date to Numeric in R
How to Convert Numeric to Character in R
How to Convert Categorical Variables to Numeric in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories