How to Convert Date to Numeric in R?
Last Updated :
19 Dec, 2021
In this article, we will discuss how to convert date to numeric in R Programming Language.
Method 1: Using as.numeric()
This function is used to convert date into numeric
Syntax:
as.numeric(date)
where the date is the input date.
Example:
R
data = as.POSIXct ( "1/1/2021 1:05:00 AM" ,
format= "%m/%d/%Y %H:%M:%S %p" )
print (data)
print ( as.numeric (data))
|
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
If we want to get the number of days from the number, divide the number by 86400.
as.numeric(date)/86400
If we want to get the number of years from date, then divide it by 365.
as.numeric(date)/86400/365
Example: R program to convert dates into days and years
R
data = as.POSIXct ( "1/1/2021 1:05:00 AM" ,
format= "%m/%d/%Y %H:%M:%S %p" )
print (data)
print ( as.numeric (data))
print ( as.numeric (data)/86400)
print (( as.numeric (data)/86400)/365)
|
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
[1] 18628.05
[1] 51.03574
Method 2: Use functions from lubridate package
Here, By using this module, we can get the day, month, year, hour, minute, and second separately in integer format.
Syntax:
day:
day(date)
month:
month(date)
year:
year(date)
hour:
hour(date)
minute:
minute(date)
second:
second(date)
Example:
R
library ( "lubridate" )
data = as.POSIXct ( "1/1/2021 1:05:00 AM" ,
format= "%m/%d/%Y %H:%M:%S %p" )
print (data)
print ( day (data))
print ( month (data))
print ( year (data))
print ( hour (data))
print ( minute (data))
print ( second (data))
|
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1
[1] 1
[1] 2021
[1] 1
[1] 5
[1] 0
Share your thoughts in the comments
Please Login to comment...