How to Convert Date to Numeric Format in R

Date objects are saved in R language as integer values, allowing for dates to be compared and manipulated as you would a numeric vector. Converting the date from one format to another format is a common operation in a programming language, and R is no different. In today’s tutorial, we will see how to convert the date into the numeric format with an example.

How to Convert Date to Numeric

To convert Date to Numeric format in R, use the as.POSIXct() function and then you can coerce it to a numeric value using as.numeric() function. The as.POSIXct() is one of the Date-Time conversion functions. It belongs to as.POSIX* class provides the functions to manipulate objects of classes “POSIXlt” and “POSIXct” representing calendar dates and times.

Example

dt <- as.POSIXct("11/20/1993 11:02:00 PM", format = "%m/%d/%Y %H:%M:%S %p")
numeric <- as.numeric(dt)
numeric

Output

[1] 753773520

Here, the output numeric value you get shows the number of seconds since an arbitrary date, usually 1/1/1970.

as.Date.numeric in R

The as.Date.numeric class provides Date Conversion Functions From Numeric, Integer, and Ts Objects. It provides functions to convert numeric and related classes to objects of class “Date” representing calendar dates.

Syntax

## S3 method for class 'numeric':
as.Date(x, origin = "1970-01-01", \dots)

## S3 method for class 'ts':
as.Date(x, offset = 0, \dots)

Examples

as.Date(0, origin = "1970-01-01")
as.Date(0:4, origin = "1970-01-01")

Output

[1] "1970-01-01"

[1] "1970-01-01" "1970-01-02" "1970-01-03" "1970-01-04" "1970-01-05"
[6] "1970-01-06" "1970-01-07" "1970-01-08" "1970-01-09" "1970-01-10"

See another example.

x <- ts(rnorm(10), start = 0)
as.Date(unclass(time(x)), origin = "1970-01-01")

Output

[1] "1970-01-01" "1970-01-02" "1970-01-03" "1970-01-04" "1970-01-05"
[6] "1970-01-06" "1970-01-07" "1970-01-08" "1970-01-09" "1970-01-10"

That is it for Converting Date to Numeric Format in R Tutorial.

Leave a Comment