0

I'm writing a function that will take my df$date field (which is daily POSIXct date (by day) and create a new variable called df$wbm (wbm = week beginning Monday). I know the math works because I've done this in Excel but the syntax is not working, see below:

df$wbm<- if (weekdays(df$date) == "Sunday") {
  df$date - days(6)
} else { df$date + (days(2) - df$date)
  }
dre
  • 474
  • 5
  • 19
  • Possible duplicate of [How to get week starting date from a date in R](https://stackoverflow.com/questions/43521371/how-to-get-week-starting-date-from-a-date-in-r) – Shree Nov 20 '18 at 22:38

2 Answers2

0

%w might be the format argument you're looking for: it's day of week where Sunday is 0

> x <- as.POSIXct('2018-11-20 12:12:12')
> format(x, "%w")
[1] "2"
12b345b6b78
  • 995
  • 5
  • 16
0

Looked through several of the links, I found the last answer here to be the most helpful: How to find Previous Sunday in R

This is what I came up with, using lubridate:

> df$wbm<- lubridate::floor_date(df$date, "week") + days(1)
> weekdays(df$wbm)[1]
[1] "Monday"
dre
  • 474
  • 5
  • 19