Vinay billa Vinay billa - 10 months ago 58
R Question

How to convert integer into date format in r?

Hi I have a column which is named as Week but is of class integer. It looks like this


These are essentially the weeks in 2014. I want to convert them into week ending dates like

201401 = 2014-01-05

201402 = 2014-01-12

Thank You.

Ps. I tried to google the answer for this but could not get the relevant one. Also as.Date does not work for me.

Thanks again.

Answer Source

Here is a solution:

dates <- c(201401, 201402, 201403, 201404)
as.Date(paste0(dates, '-0'), format = "%Y%W-%w")

# [1] "2014-01-05" "2014-01-12" "2014-01-19" "2014-01-26"

%W is the week number and we had the -0 to get the last day (Sunday) of the week (%w goes from 0 to 6).

You can look at help("strptime") to get more information on dates manipulation.