Character dates to date conversions

I am attempting to parse a character vector that has dates represented by following character format: SEP0, OCT0...JAN1, etc. The SEP is the month, and the 0 or 1 is the year 2020 or 2021, etc. I am trying to convert the characters into a dates with the following format: 2020-09-01, 2020-10-01...2021-01-01, etc. I'm trying different things with lubridate, but I can't seem to get it to work. Still very new with dates, so I'm likely messing something up here.

Thanks in advance.

######## converting character to dates ########
data <-c("SEP0", "OCT0", "DEC0", "JAN1")

new_data <- as_date(data, "ymd") # failed

new_data2 <- mutate(data, Year = year(Mth), Month = month(Mth), Day = "01", 
                   date = as_date(paste0(Year, Month,"01"))) # also failed

Try this. As written, it will only work for 2020 through 2029.

library(stringr)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
data <-c("SEP0", "OCT0", "DEC0", "JAN1")
data <- sub(pattern = "(...)(.)", replacement = "202\\2-\\1-01", data)
data
#> [1] "2020-SEP-01" "2020-OCT-01" "2020-DEC-01" "2021-JAN-01"
data <- ymd(data)
data
#> [1] "2020-09-01" "2020-10-01" "2020-12-01" "2021-01-01"

Created on 2020-08-18 by the reprex package (v0.3.0)

suppressPackageStartupMessages({
  library(dplyr)
  library(lubridate)
  library(stringr)})

date_1 <- "Oct1"
date_2 <- "Sep0"
to_date <- function(x) {
    case_when(
      str_detect(x,"0") == TRUE ~ 
        str_replace(x,"0","-01-2020") %>% mdy(),
      str_detect(x,"1") == TRUE ~ 
        str_replace(x,"1","-01-2021") %>% mdy()
      )
}
to_date(date_1)
#> Warning: All formats failed to parse. No formats found.
#> [1] "2021-10-01"
to_date(date_2)
#> Warning: All formats failed to parse. No formats found.
#> [1] "2020-09-01"

Created on 2020-08-18 by the reprex package (v0.3.0)

Despite warning message, still returns a Date object

1 Like

@technocrat hi there,
you don't need the == TRUE in your case_when :wink:
very nice solution though!

1 Like

Helpful - Thank-you.

Good solution. Thanks.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.