Tanga94
Tanga94

Reputation: 837

How to keep vector as date class in R when changing format of dates

I have the following vector of dates in R. I would like to convert it from character class into Date class, however I only want to display the dates as year-month (%Y-%m) instead of year-month-day (%Y-%m-%d)

library(tidyverse)

dates <- structure(list(Date = c("2022-03-24", "2022-04-21", "2022-05-24", 
                        "2022-07-22", "2022-09-01")), row.names = c(NA, -5L), class = c("tbl_df", 
                                                                                        "tbl", "data.frame"))

dates %>% 
  mutate(Date = format(as.Date(Date), '%Y-%m'))

when using format to convert the dates to %Y-%m, is there a way to maintain the class of the vector as <date> instead of as a character <chr>?

# A tibble: 5 x 1
  Date      
  <chr>     
1 2022-03-24
2 2022-04-21
3 2022-05-24
4 2022-07-22
5 2022-09-01

Upvotes: 3

Views: 639

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389175

A base R option -

You can change the last two digits of the date with 01.

as.Date(sub('\\d{2}$', '01', dates$Date))
#[1] "2022-03-01" "2022-04-01" "2022-05-01" "2022-07-01" "2022-09-01"

Upvotes: 0

akrun
akrun

Reputation: 887551

We may use floor_date to normalize the day to a single constant value from the Dates

library(lubridate)
library(dplyr)
dates %>%
    mutate(Date2 = floor_date(ymd(Date), "month"))

-output

# A tibble: 5 × 2
  Date       Date2     
  <chr>      <date>    
1 2022-03-24 2022-03-01
2 2022-04-21 2022-04-01
3 2022-05-24 2022-05-01
4 2022-07-22 2022-07-01
5 2022-09-01 2022-09-01

Or another option is to assign the day

dates$Date2 <- ymd(dates$Date)
day(dates$Date2) <- 1
> dates
# A tibble: 5 × 2
  Date       Date2     
  <chr>      <date>    
1 2022-03-24 2022-03-01
2 2022-04-21 2022-04-01
3 2022-05-24 2022-05-01
4 2022-07-22 2022-07-01
5 2022-09-01 2022-09-01

Upvotes: 2

Related Questions