-1

Here's a sample of my data

# A tibble: 300 x 5
    year week  department_id media_tpv mediana_tpv
   <dbl> <chr>         <dbl>     <dbl>       <dbl>
 1  2019 00                3      90.4         65 
 2  2019 00                5     194.         117.
 3  2019 00               65     173.         117.
 4  2019 00               93     183.         105 

Now, say I want to construct a tsibble::yearweek()-based index from it. I tried pasting year and week toghether, then passing it to yearweek() but it failed to parse correctly.

dput:

df <- structure(list(year = c(2019, 2019, 2019, 2019), week = c("00", 
"00", "00", "00"), department_id = c(3, 5, 65, 93), media_tpv = c(90.4, 
194, 173, 183), mediana_tpv = c(65, 117, 117, 105)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))
Pedro Cavalcante
  • 414
  • 4
  • 14

1 Answers1

1

You just need to coerce the two columns into the format that yearweek looks for:

df$week <- paste0('W', df$week)
df$yearweek <- paste0(df$year, ' ', df$week)
yearweek_column <- yearweek(df$yearweek)

Then you can check:

print(yearweek)

Which gives you:

[1] "2018 W52" "2018 W52" "2018 W52" "2018 W52"

tidyverse solution:

df %>%
  mutate(week = paste0('W', week),
         yearweek = paste0(year, ' ', week),
         yearweek_column = yearweek(yearweek))
Matt
  • 7,255
  • 2
  • 12
  • 34