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
CodePudding user response:
We may use floor_date
to normalize the day to a single constant value from the Date
s
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