You can use the as.Date() function to convert a datetime to a date in R.
This function uses the following basic syntax:
df$date <- as.Date(df$datetime)
The following example shows how to use this syntax in practice.
Example: Convert Datetime to Date in R
Suppose we have the following data frame in R that contains information about sales made at some store:
#create data frame df <- data.frame(dt=as.POSIXct(c('2023-01-01 10:14:00 AM', '2023-01-12 5:58 PM', '2023-02-23 4:13:22 AM', '2023-02-25 10:19:03 PM')), sales = c(12, 15, 24, 31)) #view data frame df dt sales 1 2023-01-01 10:14:00 12 2 2023-01-12 05:58:00 15 3 2023-02-23 04:13:00 24 4 2023-02-25 10:19:00 31
The dt column contains the date and time of the sale.
We can use the class() function to view the class of this column:
#view class of dt column
class(df$dt)
[1] "POSIXct" "POSIXt"
We can see that the dt column currently has a class of POSIXct, which is a datetime class.
To convert this column to a date, we can use the as.Date() function:
#convert dt column to date df$dt <- as.Date(df$dt) #view updated data frame df dt sales 1 2023-01-01 12 2 2023-01-12 15 3 2023-02-23 24 4 2023-02-25 31
Notice that the time has been dropped from each datetime value in the dt column.
We can verify that the dt column now has a date class by using the class() function:
#view class of dt column
class(df$dt)
[1] "Date"
We can see that the dt column is indeed a date now.
Related: A Quick Guide to as.Date() Function in R
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Generate a Sequence of Dates in R
How to Convert Strings to Dates in R
How to Calculate Number of Months Between Dates in R