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.
A simple base-R way if your dates are properly coded as date class in R: as.Date(unclass(dates)-unclass(dates)%%7-3)
. You unclass it do get number of days since 1970-01-01. Then subtract remainder from division on 7 (day of the week!). Then subtract 3 because 1970-01-01 was Thursday –
Also you can group your data by week, and then create a column of "minimal date of that week". Here is how to do it in data.table
package:
df=data.table(df)
df[,lastMonday:=min(dates),by=.(week(dates))]
It should work if you dont have spaces in dates. Also, in some locales week starts with sunday, so you should be careful. And you will need additional grouping variable, if your dates span for more than a year