0

My goal is to take a character vector of dates formatted as YYYY-MM-DD HH-MM-SS and get just MM-YYYY. Here is my code:

    EndDate <- c("2020-10-01 10:37:38", "2020-11-01 10:42:48") #character string with hms
    EndDate <- as.Date(ymd_hms(EndDate)) #wrap ymd_hms in as.Date to strip hms

It works up to this point, but here is where it falls apart.

    EndDate <- format(EndDate, "%m-%Y") #returns a character vector
    EndDate <- as.Date(EndDate, format = "%m-%Y") #returns a date vector of NAs

I'm not sure what is causing the NAs or what I'm doing wrong.

Stephen Poole
  • 371
  • 3
  • 9
  • 2
    R believes that a "date" must have a day-of-month, perhaps weird (not really). Because of this, no string that is `%m-%Y` or `%B-%Y` or whatever will be converted to a `Date` class, period. Some packages have "month-year" object types, but native R does not. See https://stackoverflow.com/q/6242955/3358272 – r2evans Mar 08 '22 at 18:29
  • 1
    Please confirm that that comment resolves your issue: you cannot have `Date` with only month and year. You can have strings that are formatted that way, but they won't be numeric. If you need number-like, then I suggest decimal years (e.g., "October 2020" would be `2020 + (10-1)/12 = 2020.75`). – r2evans Mar 08 '22 at 18:34
  • 1
    StephenPoole, the vote-to-close has started, you might want to comment sooner rather than later ... – r2evans Mar 08 '22 at 18:41
  • 1
    You could: `paste(month(EndDate1), year(EndDate1), sep = "-")`. Will give: `"10-2020" "11-2020"` or `strftime(EndDate, "%m-%Y")`. – TarJae Mar 08 '22 at 18:42

0 Answers0