Date data type is very important for all programming languages. To handle the date in a proper way, we need to apply some formatting logic.
This is the case for R programming language as well. This post explains you, how we can handle the Date data in R. There are different functions available in R to handle date.
To get the today’s date, use Sys.Date()
Sys.Date()
> Sys.Date()
[1] “2018-05-22”
To get date and time, use date()
> date()[1] “Tue May 22 15:29:18 2018”
Check the below list of symbols to play with date and time format.
Symbol | Meaning | Example |
%d | day as a number (0-31) | 01-31 |
%a %A |
abbreviated weekday unabbreviated weekday |
Mon Monday |
%m | month (00-12) | 00-12 |
%b %B |
abbreviated month unabbreviated month |
Jan January |
%y %Y |
2-digit year 4-digit year |
07 2007 |
> today <- Sys.Date()> format(today, format=”%B %d %Y”)[1] “May 22 2018”
Date Conversion
In a real-time scenario, we will not get date as date data type. Always, we need to convert to proper date data type. To convert to date data type, we need to use as.Date() function.
Syntax
as.Date(x, “format”)
x – Field or column
format – use the above symbols to frame the proper format.
DateVec<- c(“01/05/2018”, “08/16/2018”)
DateVec
[1] “01/05/2018” “08/16/2018”
summary(DateVec)
Length Class Mode
2 character character
dates <- as.Date(DateVec, “%m/%d/%Y”)
dates
[1] “2018-01-05” “2018-08-16”
summary(dates)
Min. 1st Qu. Median Mean 3rd Qu. Max.
“2018-01-05” “2018-03-01” “2018-04-26” “2018-04-26” “2018-06-21” “2018-08-16”
About the Author