How to use as.Date() Function In R Language
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.
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, …)
Parameters:
- 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.
Returns:
This function will be returning the date to the user.
Example
First, create a factor with the Date dataset
R
# Original factor date 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) |
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
Convert the factor to a Date object with the format with the same
R
# Convert the factor to a Date object with the format %Y-%m-%d gfg_dates <- as.Date (gfg_factor, format = "%Y-%m-%d" ) print ( class (gfg_dates)) print (gfg_dates) |
Output:
[1] "Date"
[1] "2021-05-02" "2022-01-07" "2000-12-17" "2021-03-23" "2021-04-11"
Format the Date object as %d %B %Y (day, month name, year)
Python3
# Format the Date object as %d %B %Y (day, month name, year) formatted_date < - format (gfg_dates, format = "%d %B %Y" ) print (formatted_date) print ( class (formatted_date)) # Convert the formatted character date back to a Date object formatted_date1 < - as.Date(formatted_date, format = "%d %B %Y" ) # Print the converted Date object print (formatted_date1) print ( class (formatted_date1)) |
Output:
[1] "02 May 2021" "07 January 2022" "17 December 2000" "23 March 2021"
[5] "11 April 2021"
[1] "character"
[1] "2021-05-02" "2022-01-07" "2000-12-17" "2021-03-23" "2021-04-11"
[1] "Date"
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.