1

I want to determine the month based on the year and the week number. This problem is unique because it's missing the day of week information needed in these examples Transform year/week to date object, Convert week number to date.

year <- c("2017", "2017", "2018")
week <- c("37", "53", "01")
month <- lubridate::month(as.Date(paste0(year, "-", week), format = "%Y-%V"))

> month
[1] 9 9 9

For some reason this returns 9 for each element in my vector. September is the correct month for the first observation, but this cannot be the case for the remaining two.

Expected output:

> month
[1] 9 12 1

Edit: It turns out that this task is unlikely to be solved without knowing the day of week. I'll try to find a workaround to the year/date to avoid this problem altogether.

philiporlando
  • 941
  • 4
  • 19
  • 31
  • 1
    https://stackoverflow.com/questions/32470414/convert-week-number-to-date or https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object – Jon Spring Sep 25 '18 at 19:28
  • I have already tried following these examples. They are using the `%U` week format instead of the `%V` format. When I use `%U` I get an `NA` when the week is `53`. When I use the `%V` format, each month is `9`... These examples also have a 'day' or 'weekday' element that I am missing. – philiporlando Sep 25 '18 at 19:34
  • Ahhh good point... I'll have to figure something else out then. – philiporlando Sep 25 '18 at 19:53
  • 1
    Not precise, but might be good enough: library(lubridate); library(magrittr); `paste(year, 1,1) %>% ymd %>% add(as.numeric(week) * 7) %>% month()` – Jon Spring Sep 25 '18 at 19:57

1 Answers1

-2

Try this:

> year <- c(2017, 2017, 2018)
> week <- c(37, 53, 01)
> month <- lubridate::month(as.Date(paste0(year, "-", week, "-", 10), format = "%Y-%U-%u"))
> month
 [1] 9 NA 1

The reason you get NA here, because it will calculate months upto 52nd week.

ari
  • 857
  • 9
  • 10
  • 1
    Can you explain why you are using a `10` for the day of week? – philiporlando Sep 25 '18 at 20:16
  • 1
    You need to add a **date** as you'll have to specify Year-month-date format. You can put any date ranging 1-30 – ari Sep 25 '18 at 20:19
  • Standard says it should be 1-7, but you can put any integer. This date part is simply ignored when you have **lubridate:month** – ari Sep 25 '18 at 20:35