as.Date() function in R is a built-in function that converts a character vector of strings into a date object. It takes a vector of the form c(“yyyy-mm-dd”, “hh:mm:ss”) or a character vector of the form “yyyy-mm-dd” and converts it into a date object of the same format if possible. Otherwise, it returns NA.
This guide will explain how to use the as.Date() function in R.
Syntax
as.date(x, format = "%y/%m/%d")
Arguments
- x = a character or string representation of the date.
- format = specifies how to interpret x. It can be one of the formats, including “dmy”, “ymd”, or “mdy”. The default format is “ymd”.
Kindly note that format is either “ymd” for the year-month-day format, “dmy” for the day-month-year format, “mdy” for the month-day-year format, or “ymdy” for year-month-day of week order with weekday names from 1 through 7 (e.g., Monday).
Example 1: Converting Character String to Date With Default Format
In this example, we will not use the format parameter. Hence, by default, it will consider the “ymd” format.
#creating a character string of ymd format
x <- '2022-09-06'
#check class of x
class(x)
[1] "character"
#converting character to date format
date_val <- as.Date(x)
#check class of date_val
class(date_val)
[1] "Date"
Example 2: Converting Character String to Date With Format Parameter
In this example, we will use the “dmy” date format.
#creating a character string of %d-%m-%y format
x <- "09-06-2022"
#check class of x
class(x)
[1] "character"
#converting character to date format
date_val <- as.Date(x, format="%d-%m-%Y")
#print date_val
date_val
[1] "2022-06-09"
#check class of date_val
class(date_val)
[1] "Date"