Henry Henry - 3 months ago 12
R Question

Find most recent Monday for a dataframe

I have a dataframe object, and among the fields in it, I have a dates:

df$dates


I need to add a column which is 'Week Starting', i.e.

df[,'WeekStart']= manipulation


Where the week start is the date of the Monday of that week. i.e.: today is Thursday 24/09/15, would have an entry as '21-Sept'. Next thursday, 01/10/15, would be '28-Sept'.

I see that there is a
weekday()
function which will convert a day into a week-day, but how can I deal with this
most recent monday
?

rbm rbm
Answer

Simples:

dates <-(Sys.Date()+1:30)
week.starts <- as.Date(sapply (dates, function(d) { return (d + (-6 - as.POSIXlt(d)$wday %% -7 ))}), origin = "1970-01-01")

and running as

d <- data.frame(dataes=dates, monday=week.starts)

gives

       dataes     monday
1  2015-09-25 2015-09-21
2  2015-09-26 2015-09-21
3  2015-09-27 2015-09-21
4  2015-09-28 2015-09-28
5  2015-09-29 2015-09-28
6  2015-09-30 2015-09-28
7  2015-10-01 2015-09-28
8  2015-10-02 2015-09-28
9  2015-10-03 2015-09-28
10 2015-10-04 2015-09-28
11 2015-10-05 2015-10-05
12 2015-10-06 2015-10-05
13 2015-10-07 2015-10-05
14 2015-10-08 2015-10-05
15 2015-10-09 2015-10-05
16 2015-10-10 2015-10-05
17 2015-10-11 2015-10-05
18 2015-10-12 2015-10-12
19 2015-10-13 2015-10-12
20 2015-10-14 2015-10-12
21 2015-10-15 2015-10-12
22 2015-10-16 2015-10-12
23 2015-10-17 2015-10-12
24 2015-10-18 2015-10-12
25 2015-10-19 2015-10-19
26 2015-10-20 2015-10-19
27 2015-10-21 2015-10-19
28 2015-10-22 2015-10-19
29 2015-10-23 2015-10-19
30 2015-10-24 2015-10-19

Similar approach, example:

# data
d <- data.frame(date = as.Date( c("20/09/2015","24/09/2015","28/09/2015","01/10/2015"), "%d/%m/%Y"))

# get monday
d$WeekStart <- d$date - 6 - (as.POSIXlt(d$date)$wday %% -7)

d
# result
#         date  WeekStart
# 1 2015-09-20 2015-09-14
# 2 2015-09-24 2015-09-21
# 3 2015-09-28 2015-09-28
# 4 2015-10-01 2015-09-28