0

I have a character vector containing dates in the format "YYYY-MM", such as:

date_vec <- c("2020-01", "2020-02", "2020-03", "2020-04")

I want to convert this vector to a Date format in R, but I want to keep only the year and month information without adding any information about the day of the month. Specifically, I want the resulting Date objects to have the format "%Y-%m" and not "%Y-%m-%d".

I have tried using the as.Date() function in R with the format argument set to "%Y-%m", but this seems returns NA.

as.Date(date_vec, format = "%Y-%m")
#return NA NA NA NA

Any thoughts, please?

Mukhtar Abdi
  • 391
  • 1
  • 12
  • 1
    It's not possible to create a `Date` object/vector without "day", hence your NAs. Packages like `yearmon` create a numeric vector inside a custom index class so it's not a `Date` object, just a representation. `lubridate` will convert your strings to `Date`, but it will add a day if it's missing. It would be useful to know why you need these in `Date` format. Are you wanting to conduct time series analysis or similar? It's just that unless you absolutely need a `Date` object for a particular process, there are numerous options for conducting analysis that can call the d/m/y parts in a string. – L Tyrone Apr 15 '23 at 10:38

1 Answers1

3

If you want to work with just months, you can use zoo's yearmon class.

EDIT: Simplified answer thanks to G. Grothendieck's suggestion.

date_vec <- c("2020-01", "2020-02", "2020-03", "2020-04")

zoo::as.yearmon(date_vec)

[1] "Jan 2020" "Feb 2020" "Mar 2020" "Apr 2020"
NicChr
  • 858
  • 1
  • 9
  • 1
    Probably best to use `library(zoo)` and omit the `zoo::` before `as.yearmon` in case there are further calculations with the yearmon object to be sure it can find further yearmon methods. For example, if in a fresh instance of R we write `x <- zoo::as.yearmon("2000-01"); as.Date(x)` then we would get an error since it would not be able to find the `as.Date.yearmon` method. If we write `library(zoo); x <- as.yearmon("2000-01"); as.Date(x)` there would be no problem. – G. Grothendieck Apr 15 '23 at 17:25