Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting weeks of year to dates

I have a data set with number of weeks from the beginning of the year (%W), which I would like to convert to dates in order to plot it using date on x-axis

dat <- structure(data.frame(week = c(22, 34, 15), year = c(2009, 2009, 2010), x = c(3.4, 5.2, 1.3)))

I try to convert the weeks based on earlier questions here, but end up getting "YYYY-10-01" for each date.

as.Date(paste("01", dat$week, dat$year, sep = "-"), format = "%d-%W-%Y")

Why is this and how can do it right?

like image 595
Mikko Avatar asked Oct 08 '12 17:10

Mikko


People also ask

How do I convert weeks to days in Excel?

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 you convert a week number to a date in sheets?

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).

How do you convert weeks to months?

If you just need to get the month as Arabic number, you can use this formula =MONTH(DATE(A2,1,B2*7-2)-WEEKDAY(DATE(B2,1,3))). Tip: In the above formulas, A2 indicates the year cell, B2 is the week number cell.


1 Answers

Try this instead:

as.Date(paste("1", dat$week, dat$year, sep = "-"), format = "%w-%W-%Y")

A week and a year don't specify a date, so you do need a "day", but you need the "day of the week", or %w, rather than "day of the month", or %d. In this case, I used Monday (i.e. 1). Also, apparently %w doesn't like leading zeros.

like image 124
joran Avatar answered Oct 31 '22 02:10

joran