Here are two ways to convert Date to Numeric in R:
- Using the as.numeric() function
- Using the lubridate package
Method 1: Using as.numeric() function
Before using the “as.numeric()” function, you must create a date object using the “as.POSIXct()” function and then convert the date to numeric.
date: It is a date object that needs to be converted to numeric.
today_date <- as.POSIXct("2023-02-24 13:09:00", tz = "GMT") as.numeric(today_date)
Applying an as.numeric() function to a POSIXct object will return the number of seconds since January 1, 1970 (the Unix epoch) at the specified date and time.
However, you need to know the time zone used in your POSIXct object to get the correct result.
Method 2: Using a lubridate package
To use the lubridate package, you must “install and load” the lubridate package using install.packages(“lubridate”).
After that, you must import the package using the library(lubridate) function at the top of the file.
Then, you can use different functions from the package to extract different time units from your date object.
library(lubridate) #get year value in date object year(date) #get seconds value in date object second(date) #get minutes value in date object minute(date)
library(lubridate) today_date <- as.POSIXct("2023-02-24 13:09:00", tz = "GMT") hour(today_date) minute(today_date) second(today_date) day(today_date) month(today_date) year(today_date)
 13  9  0  24  2  2023