Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert week number to date

Tags:

I have a data frame in R with the week of the year that I would like to convert to a date. I know I have to pick a year and a day of the week so I am fixing those values at 2014 and 1. Converting this to a date seems simple:

as.Date(paste(2014,df$Week,1,sep=""),"%Y%U%u") 

But this code only works if week is greater than 9. Week 1 - 9 returns NA. If I change the week to 01,02,03... it still returns NA.

Anyone see what I am missing?

like image 916
Aaron Soderstrom Avatar asked Sep 09 '15 03:09

Aaron Soderstrom


People also ask

How do you convert weeks to date?

Select a blank cell you will return the week number, enter this formula: =WEEKNUM(B1,1), and press the Enter key. See screenshot: Notes: (1) In above formula, B1 contains the date that you want to use.

How do I convert a week number to a month in Excel?

Click the cell that you want to get month and type this formula =CHOOSE(MONTH(DATE(A2,1,B2*7-2)-WEEKDAY(DATE(B2,1,3))),"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") into it, then press Enter key to get the result, and then drag auto fill to ...

How do you get the date from a week number excel?

How to get the date from a week number. To get the date of the Monday in a week, use =DATE( A1 , 1, -3 + 7 * B1 - WEEKDAY(DATE( A1 , 1, 4), 2) + 1) . Cell A1 contains the four-digit year (e.g. 2022), and cell B2 contains the week number (1-53).


2 Answers

as.Date is calling the 1 to 9 as NA as it is expects two digits for the week number and can't properly parse it.

To fix it, add in some - to split things up:

as.Date(paste(2014, df$Week, 1, sep="-"), "%Y-%U-%u") 
like image 151
jeremycg Avatar answered Oct 29 '22 16:10

jeremycg


An alternative solution is to use date arithmetic from the lubridate package:

lubridate::ymd( "2014-01-01" ) + lubridate::weeks( df$Week - 1 ) 

The -1 is necessary because 2014-01-01 is already week 1. In other words, we want:

  • df$Week == 1 to map to 2014-01-01 (which is ymd("2014-01-01") + weeks(1-1))
  • df$Week == 2 to map to 2014-01-08 (which is ymd("2014-01-01") + weeks(2-1))
  • and so on.
like image 26
Artem Sokolov Avatar answered Oct 29 '22 15:10

Artem Sokolov