1

I have this data frame:

dat = data.frame(date = as.Date(c("2016-12-01","2016-12-02","2016-12-03","2016-12-04",
                                  "2016-12-05","2016-12-06","2016-12-07","2016-12-08",
                                  "2016-12-09","2016-12-10","2016-12-11","2016-12-12",
                                  "2016-12-13","2016-12-14","2016-12-15")))

> dat
         date
1  2016-12-01
2  2016-12-02
3  2016-12-03
4  2016-12-04
5  2016-12-05
6  2016-12-06
7  2016-12-07
8  2016-12-08
9  2016-12-09
10 2016-12-10
11 2016-12-11
12 2016-12-12
13 2016-12-13
14 2016-12-14
15 2016-12-15

I'd like to add a column that is the week ending FRIDAY's date so the results would be

         date  new column
1  2016-12-01      2016-12-02
2  2016-12-02       2016-12-02
3  2016-12-03       2016-12-09
4  2016-12-04       2016-12-09
5  2016-12-05       2016-12-09
6  2016-12-06       2016-12-09
7  2016-12-07       2016-12-09
8  2016-12-08       2016-12-09
9  2016-12-09       2016-12-09
10 2016-12-10       2016-12-16
11 2016-12-11       2016-12-16
12 2016-12-12       2016-12-16
13 2016-12-13       2016-12-16
14 2016-12-14       2016-12-16
15 2016-12-15       2016-12-16

etc....what's the best way to do that?

Jaap
  • 81,064
  • 34
  • 182
  • 193
user3022875
  • 8,598
  • 26
  • 103
  • 167
  • May want to look into this question and the libridate package. https://www.google.ca/url?sa=t&source=web&rct=j&url=http://stackoverflow.com/questions/26966139/r-how-to-determine-the-week-ending-date&ved=0ahUKEwiyvuDe_efQAhVGyGMKHZW9AOUQFggaMAA&usg=AFQjCNERaF0Ch14R8MC05pUR2OSbbnsiMg&sig2=0o805go7yp_BCBMWJ96aKA – user3366016 Dec 09 '16 at 20:50

1 Answers1

1

A solution with base R:

dat$friday <- dat$date - (as.integer(format(dat$date, '%w')) - 5)

which gives:

> dat
         date     friday
1  2016-12-01 2016-12-02
2  2016-12-02 2016-12-02
3  2016-12-03 2016-12-02
4  2016-12-04 2016-12-09
5  2016-12-05 2016-12-09
6  2016-12-06 2016-12-09
7  2016-12-07 2016-12-09
8  2016-12-08 2016-12-09
9  2016-12-09 2016-12-09
10 2016-12-10 2016-12-09
11 2016-12-11 2016-12-16
12 2016-12-12 2016-12-16
13 2016-12-13 2016-12-16
14 2016-12-14 2016-12-16
15 2016-12-15 2016-12-16

Explanation:

  • With format(dat$date, '%w') you extract the weekdaynumber from the date-column.
  • Convert that to an integer and substract 5 (the weekdaynumber of friday).
  • Substract the result from the date and you get the date of te friday of that week.
Jaap
  • 81,064
  • 34
  • 182
  • 193