1

I have the following data frame. How do I convert the week numbers to months. I don't want a date(mm-dd-yyyy). I am thinking of writing a loop but any better suggestions are welcomed.

    Week product  quantity
0    1    coke       1.5
1    3    fanta      1.7
2    7    coke       3.6
3    23   sprite     2.4
4    26   pepsi      2.9 

This is the result i'd like to achieve.

   Week product  quantity  Month
0    1    coke       1.5   January
1    3    fanta      1.7   January
2    7    coke       3.6   February
3    10   sprite     2.4   March
4    13   pepsi      2.9   April
Riff
  • 107
  • 1
  • 8
  • 1
    Take a look at `lubridate::month( x, label = TRUE, abb = FALSE )`, where `x` is your vector of dates parsed from the week number via `lubridate::ymd( "2017-01-01" ) + lubridate::weeks( c(1,3,7,10,13) )` – Artem Sokolov Sep 12 '17 at 18:35
  • I'd like to have multiple opinions on how best to tackle this problem . Please remove the duplicate classification – Riff Sep 12 '17 at 18:41
  • If you want the month names after the solution using `as.Date/paste` in the link given, use `strftime` with `format = "%B"`. – Rui Barradas Sep 12 '17 at 18:45
  • I've just tested the new solution of @ArtemSokolov and the months are different. With `as.Date/paste`, the last month is June, with `lubridate` it's July. (Year is 2014.) – Rui Barradas Sep 12 '17 at 18:51
  • 1
    Oh, sorry. You want to subtract `1` from your `df$Week`, because `2014-01-01` is already week 1: `lubridate::ymd( "2017-01-01" ) + lubridate::weeks( c(1,3,7,10,13) - 1 )`. It's basically 0-based vs. 1-based indexing. – Artem Sokolov Sep 12 '17 at 18:57
  • @ArtemSokolov Yes, that does it, the two results are now the same. – Rui Barradas Sep 12 '17 at 19:12
  • Do you have a start date of your observations? Is there agreement on which day starts the week? Are you ok with the weeks that straddle two months being "given" to one of those two months? – bf2020 Sep 12 '17 at 20:50
  • Beware of the different conventions on how to count week-of-the-year. Please, see [this answer](https://stackoverflow.com/a/45587644/3817004) for a discussion. – Uwe Sep 14 '17 at 07:16

0 Answers0