0

I would like to create a column in a data frame that is of type date but is formatted like %Y-%m.

For example,

# create data frame
df <- tibble::tibble(
  date = lubridate::ymd("2023-01-01","2023-01-02","2023-01-03",
                        "2023-01-04","2023-01-05","2023-01-06","2023-01-07",
                        "2023-01-08","2023-01-09","2023-01-10")
)

# we can see that the date column has type "date"
df
#> # A tibble: 10 x 1
#>    date      
#>    <date>    
#>  1 2023-01-01
#>  2 2023-01-02
#>  3 2023-01-03
#>  4 2023-01-04
#>  5 2023-01-05
#>  6 2023-01-06
#>  7 2023-01-07
#>  8 2023-01-08
#>  9 2023-01-09
#> 10 2023-01-10

# but when I try to reformat it, it becomes type "chr"
df |>
  dplyr::mutate(
    date = format(date, format = '%Y-%m')
  )
#> # A tibble: 10 x 1
#>    date   
#>    <chr>  
#>  1 2023-01
#>  2 2023-01
#>  3 2023-01
#>  4 2023-01
#>  5 2023-01
#>  6 2023-01
#>  7 2023-01
#>  8 2023-01
#>  9 2023-01
#> 10 2023-01

Created on 2023-04-20 with reprex v2.0.2

joshbrows
  • 77
  • 7
  • 4
    because `format.Date` returns character type. If you want year month class, you could use `zoo::as.yearmon` – akrun Apr 20 '23 at 17:34
  • 4
    R only has one way to store dates and you can't change the formatting of how they print. You can only use format() to change the date value into a string that looks the way you want it to. You can't both control the formatting and have it be a date – MrFlick Apr 20 '23 at 17:34
  • This is a duplicate of [this post](https://stackoverflow.com/questions/76020986/how-to-convert-a-date-character-vector-to-date-format-while-keeping-only-year-an#comment134077506_76020986) and as others have stated, what you want is not possible. But it would be useful to know why you need these in Date format. Are you wanting to conduct time series analysis? Unless you absolutely need a Date object for a particular process, there are numerous options that can call the d/m/y parts of a date string either separately or in combination. Here, regular expressions are your friend – L Tyrone Apr 22 '23 at 04:33

0 Answers0