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?
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.
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 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).
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")
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)
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With