How to convert a factor into date format?
Factors cannot be used as a date directly thus if some functionality requires date format, a factor can be converted to one. In this article, we will be looking at two different approaches to convert factor to date in the R programming language.
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 R console and further this function will be returning the date to the user.
as.Date(): This function is used to convert between character representations and objects of class “Date” representing calendar dates.
Syntax: as.Date(x, format, tryFormats = c(“%Y-%m-%d”, “%Y/%m/%d”),optional = FALSE, …)
- x:-an object to be converted.
- format:-character string. If not specified, it will try tryFormats one by one on the first non-NA element, and give an error if none works.
- tryFormats:-character vector of format strings to try if the format is not specified.
- optional:-logical indicating to return NA if the format guessing does not succeed.
- …:-further arguments to be passed from or to other methods, including the format for as.character and as.Date methods.
This function will be returning the date to the user.
Method 2: Using ymd() Function of lubridate Package:
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:-
# Install lubridate
# load 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)
- …:-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