8

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?

Community
  • 1
  • 1
Mikko
  • 7,530
  • 8
  • 55
  • 92

1 Answers1

12

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.

joran
  • 169,992
  • 32
  • 429
  • 468