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


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 <- data.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 <- as.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 <- mdy(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

Leave a Reply

Your email address will not be published.