0

I have a hard time converting character to date in R.

I have a file where the dates are given as "2014-01", where the first is the year and the second is the week of the year. I want to convert this to a date type.

I have tried the following

z <- as.Date('2014-01', '%Y-%W')
print(z)

Output: "2014-12-05"

Which is not what I desire. I want to get the same format out, ie. the output should be "2014-01" but now as a date type.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • 1
    "2014-01" cannot be changed to date type because "2014-01" is not a valid date. An R date has only 1 valid format which is `YYYY-MM-DD` anything else is of character type. – Ronak Shah Dec 05 '22 at 03:30
  • 1
    A date requires a year, month and day, so a day and a week cannot be of type Date. You may want to distinguish between _storing_ a date versus _displaying_ a date as a string with a given format. [These answers](https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object) show how to convert year-week to Date, but to display a Date object as year-week you would use format _e.g._ `format(Sys.Date(), "%Y-%W")`. – neilfws Dec 05 '22 at 03:33

1 Answers1

2

It sounds like you are dealing with some version of year week, which exists in three forms in lubridate:

week() returns the number of complete seven day periods that have occurred between the date and January 1st, plus one.

isoweek() returns the week as it would appear in the ISO 8601 system, which uses a reoccurring leap week.

epiweek() is the US CDC version of epidemiological week. It follows same rules as isoweek() but starts on Sunday. In other parts of the world the convention is to start epidemiological weeks on Monday, which is the same as isoweek.

Lubridate has functions to extract these from a date, but I don't know of a built-in way to go the other direction, from week to one representative day (out of 7 possible). One simple way if you're dealing with the first version would be to add 7 * (Week - 1) to jan 1 of the year.

library(dplyr)
data.frame(yearweek = c('2014-01', '2014-03')) %>%
  tidyr::separate(yearweek, c("Year", "Week"), convert = TRUE) %>%
  mutate(Date = as.Date(paste0(Year, "-01-01")) + 7 * (Week-1))

  Year Week       Date
1 2014    1 2014-01-01
2 2014    3 2014-01-15
Jon Spring
  • 55,165
  • 4
  • 35
  • 53