Tuesday, November 6, 2018

How to Format the Date values in R Programming

The Date Values in R Programming
Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates.

# use as.Date( ) to convert strings to dates 
> mydates <- as.Date(c("2007-06-22", "2004-02-13"))
> mydates
[1] "2007-06-22" "2004-02-13"

> typeof(mydates)

[1] "double"
> class(mydates)
[1] "Date"

# number of days between 6/22/07 and 2/13/04
> days <- mydates[1] - mydates[2]

> days
Time difference of 1225 days

Sys.Date( ) returns today's date.
> Sys.Date( )
[1] "2018-11-05"


date() returns the current date and time.
> date()
[1] "Mon Nov 05 22:36:00 2018"

The following symbols can be used with the format( ) function to print dates.




Formatting the Date using the Format() Function :
> mydate<-Sys.Date()
> mydate
[1] "2018-11-05"


> format(mydate,"%m/%d/%Y")
[1] "11/05/2018"
> format(mydate,"%B %d %Y")[1] "November 05 2018"

> typeof(mydate)
[1] "double"
> class(mydate)
[1] "Date"


Date Conversion : Character to Date :
You can use the as.Date( ) function to convert character data to dates.

The format is as.Date(x, "format"), where x is the character data and format gives the appropriate format.

> strDates <- c("15/05/1965", "25/08/1975")
> strDates
[1] "15/05/1965" "25/08/1975"

> typeof(strDates)
[1] "character"
> class(strDates)
[1] "character"


# reading the Strings of the dates in format 'dd/mm/yyyy' and converting them to date format.
> dates <- as.Date(strDates, "%d/%m/%Y")
> dates
[1] "1965-05-15" "1975-08-25"

> typeof(dates)
[1] "double"
> class(dates)
[1] "Date"


By default R system convert to the ''yyyy-mm-dd'' format after reading.

#Converting date to the format 'mm/dd/yyyy'
> dates <- format(dates, "%m/%d/%Y")
after formatting the "dates" variable to a desired date format, it will be converted to string again.
> dates
[1] "05/15/1965" "08/25/1975"
> typeof(dates)
[1] "character"
> class(dates)
[1] "character"

Converting dates to Character data :
We can convert dates variable to character data using the as.Character( ) function.
strDates <- as.character(dates)



--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
-------------------------------------------------------------------------------------------------------- 

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.