How to use ymd() Function of lubridate Package In R Language

Under this approach to convert factor to date in r language, the user needs to call the ymd() function from the lubridate library and then pass the required parameter to this function to get the date in return from this function.

To install and import the lubridate library user needs to follow, the below syntax:-

Syntax:

# Install lubridate

install.packages("lubridate")  

# load lubridate  

library("lubridate")     

After installing and importing this library user need to call the ymd() function with the factor as its parameter.

ymd(): This function is used to transform dates stored in character and numeric vectors to Date or POSIXct objects. These functions recognize arbitrary non-digit separators as well as no separator.

Syntax: ymd(…, quiet = FALSE, tz = NULL, locale = Sys.getlocale(“LC_TIME”),truncated = 0)

Parameters:

  • …:-a character or numeric vector of suspected dates
  • quiet:-logical. When TRUE function evaluates without displaying customary messages.
  • tz:-Time zone indicator. If NULL (default) a Date object is returned. Otherwise a POSIXct with time zone attribute set to tz.
  • locale:-locale to be used, see locales.
  • truncated:-integer. Number of formats that can be truncated.

Returns: This function will always be returning dates in return

Example:

R




#install.packages("lubridate")              
 
library("lubridate")
 
gfg_factor <- factor(c("2021-05-02","2022-01-07",
                       "2000-12-17","2021-03-23",
                       "2021-04-11"))
# Print the class of gfg_factor
print(class(gfg_factor))
# Print the values
print(gfg_factor)
 
gfg_dates <- ymd(gfg_factor)
print(class(gfg_dates))
print(gfg_dates)


Output:

[1] "factor"
[1] 2021-05-02 2022-01-07 2000-12-17 2021-03-23 2021-04-11
Levels: 2000-12-17 2021-03-23 2021-04-11 2021-05-02 2022-01-07
[1] "Date"
[1] "2021-05-02" "2022-01-07" "2000-12-17" "2021-03-23" "2021-04-11"


How to convert a factor into date format?

Factors cannot be used as a date directly thus if some functionality requires a date format, a factor can be converted to one. In this article, we will be looking at two different approaches to converting factors to date in the R programming language.

Similar Reads

Method 1: Using as.Date() Function

In this method of converting factors to data using as.Date() function user needs to simply call the as.Date() function with its required parameter and the format of the date in the R console and further this function will return the date to the user....

Method 2: Using ymd() Function of lubridate Package

...