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?
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:
format(dat$date, '%w')
you extract the weekdaynumber from the date
-column.5
(the weekdaynumber of friday).Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments