Mikko Mikko - 9 months ago 48
R Question

Converting weeks of year to dates

I have a data set with number of weeks from the beginning of the year (

), 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
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?

Answer Source

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.