Hello there,
I have some year-week or week-year formats for the date index. For example: "52/2022" or: "52-2022" ; "2022/52" or "2022-52". I have done several functions for converting them to date objects. All the attempts goes in vain. Such as:
> x = "2012 25"
> parse_date_time(x, "y W")
[1] "2012-10-28 UTC"
> parse_date_time(x, "Y W")
[1] "2012-10-28 UTC"
> week = as.Date(x="2020/25",format = "%Y/%U")
> week
[1] "2020-10-28"
How can I convert these types of date formats into date objects?
Thanks in advance.
**I am a beginner shiny coder
I didn't find a library with a date parser to suit, which is why this reprex isn't overkill.
# constants
# assuming non-ISO weeks
week_starts <- seq(as.Date("2022/1/1"), by = "week", length.out = 52)
# data
input <- c("12/2022","22-2022","2022/32","2022-42")
# functions
# begins with two digits followed by separator
week_first <- function(x) {
picks = grep("^[0-9][0-9][/-]",x,value = TRUE)
ends = gsub(".....$","",picks)
index = as.numeric(ends)
return(index)
}
# ends with separator followed by two digits
week_last <- function(x) {
picks = grep("[/-][0-9][0-9]$",x,value = TRUE)
ends = gsub("^.....","",picks)
index = as.numeric(ends)
return(index)
}
extract <- function(x) c(week_first(input),week_last(input))
week_starts[extract(index)]
#> [1] "2022-03-19" "2022-05-28" "2022-08-06" "2022-10-15"
Created on 2022-10-29 by the reprex package (v2.0.1)