How to handle date in R

ByHariharan Rajendran

How to handle date in R

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

Hariharan Rajendran author

Hariharan Rajendran is a Microsoft Certified Trainer and Lead BI Solutions Consultant with 8+ years of experience in Database, BI and Azure platforms. Hariharan is also an active community leader, speaker & organizer and leads the Microsoft PUG (Power BI User Group – Chennai), SQLPASS Power BI Local Group – Chennai and an active speaker in SQL Server Chennai User Group and also a leader in Data Awareness Program worldwide events. Hariharan also frequently blogs (www.dataap.org/blog), provides virtual training (on ad-hoc basis) on Microsoft Azure, Database Administration, Power BI and database development to worldwide clients/audience.

Comments Are Closed!!!