0

I want to use the Prophet() function in R, but I cannot transform my column "YearWeek" to a as.Date() column.

I have a column "YearWeek" that stores values from 201401 up to 201937 i.e. starting in 2014 week 1 up to 2019 week 37.

I don't know how to declare this column as a date in the form yyyy-ww needed to use the Prophet() function.

Does anyone know how to do this?

Thank you in advance.

T Goose
  • 31
  • 6

1 Answers1

0

One solution could be to append a 01 to the end of your yyyy-ww formatted dates.

Data:

library(tidyverse)

df <- cross2(2014:2019, str_pad(1:52, width = 2, pad = 0)) %>%
  map_df(set_names, c("year", "week")) %>%
  transmute(date = paste(year, week, sep = "")) %>% 
  arrange(date)

head(df)
#> # A tibble: 6 x 1
#>   date  
#>   <chr> 
#> 1 201401
#> 2 201402
#> 3 201403
#> 4 201404
#> 5 201405
#> 6 201406

Now let's append the 01 and convert to date:

df %>% 
  mutate(date = paste(date, "01", sep = ""),
         new_date = as.Date(date, "%Y%U%w"))
#> # A tibble: 312 x 2
#>    date     new_date  
#>    <chr>    <date>    
#>  1 20140101 2014-01-05
#>  2 20140201 2014-01-12
#>  3 20140301 2014-01-19
#>  4 20140401 2014-01-26
#>  5 20140501 2014-02-02
#>  6 20140601 2014-02-09
#>  7 20140701 2014-02-16
#>  8 20140801 2014-02-23
#>  9 20140901 2014-03-02
#> 10 20141001 2014-03-09
#> # ... with 302 more rows

Created on 2019-10-10 by the reprex package (v0.3.0)

More info about a numeric week of the year can be found here.

tomasu
  • 1,388
  • 9
  • 11