0

I am trying to recode my time variable in my dataset. Currently, my dataset reflects data for all of December and I would like to re-code the dates so that there is a variable that includes week1, week2, week3, and week4.

My date is formatted as

december$DATE <- as.Date(december$DATE, "%m/%d/%Y")

This is my current attempt at re-coding, but to no avail:

december$week <- cut (december$DATE,
                        breaks = c(-Inf, 12/08/2016, 12/15/2016, 12/22/2016, Inf), 
                        labels=c("W1", "W2", "W3", "W4"))

The traditional way of recoding continuous into categorical is not applicable in this case. Any suggestions?

Tawk_Tomahawk
  • 139
  • 2
  • 8
  • 3
    Your question does not contain a [reproducible example](http://stackoverflow.com/q/5963269/4303162). It is therefore hard to understand your problem and give you an appropriate answer. Please make your data available (e.g. by using `dput()`) or use one of the example data sets in R. Also, add the minimal code required to reproduce your problem to your post. – Stibu Feb 23 '17 at 21:17
  • 1
    maybe try making sure your breaks are in date format, e.g. `as.Date("2016-12-08")` – Matt Tyers Feb 23 '17 at 21:18

3 Answers3

0

The ISOWeek package allows you to convert Date-objects to ISO 8601 weeks. For example,

ISOweek::ISOweek('2016-12-08')

yields

[1] "2015-W53"
salient
  • 2,316
  • 6
  • 28
  • 43
0

This could do it too:

december$week <- cut (december$DATE, 
               breaks = as.Date(c("2016-12-01", "2016-12-08", "2016-12-15", "2016-12-22", "2016-12-31")),
               labels=c("W1", "W2", "W3", "W4"))
Matt Tyers
  • 2,125
  • 1
  • 14
  • 23
0

You could consider adding a column of week numbers based on the date e.g.

require(plyr)
december$week <- format(december$date, format="%U")

Use ?strptime to see that %U gives week of the year (00–53) starting on Sunday. %V starts on a Monday etc.

amccnnll
  • 387
  • 1
  • 2
  • 15