How to find the next week in R
I want to find the closest lowest week for each date in df $ Upload_Date by specifying a series of weeks called "weeks".
head(df$Upload_Date)
#[1] "2014-09-25" "2014-09-25" "2014-09-25" "2014-11-06" "2014-09-25" "2014-09-25"
I also have a list of the weeks that I will use in the report.
> weeks
[1] "2014-08-01" "2014-08-08" "2014-08-15" "2014-08-22" "2014-08-29" "2014-09-05" "2014-09-12" "2014-09-19" "2014-09-26"
[10] "2014-10-03" "2014-10-10" "2014-10-17" "2014-10-24" "2014-10-31" "2014-11-07" "2014-11-14"
The first value in df $ Upload_Date is "2014-09-25". The nearest lower week in "weeks" is "2014-09-19". So I want to create a new column "df $ report_week" that will assign "2014-09-19" to the row with "2014-09-25".
I tried to set the following variables (not sure if this will be useful or not):
upload_day <- as.POSIXlt(df$Upload_Date[1])$yday
> upload_day
[1] 267
report_days <- as.POSIXlt(weeks)$yday
> report_days
[1] 212 219 226 233 240 247 254 261 268 275 282 289 296 303 310 317
Any ideas here?
source to share
You can try cut
and use your vector "week" like breaks
:
date <- as.Date(c("2014-09-25", "2014-10-06"))
weeks <- as.Date("2014-08-01") + 7 * 0:10
cut(date, breaks = weeks)
# [1] 2014-09-19 2014-10-03
Also note the "inline" breaks
"weeks"
where weeks start on Monday (default start.on.monday = TRUE
), as opposed to your "start on Friday-week":
cut(date, breaks = "week")
# [1] 2014-09-22 2014-10-06
source to share
You can use floor_date()
from lubridate
. Eg floor_date(x, unit = "week")
. The other answers with help are cut
very nice for the general case where you have this handy vector of weeks (or any other time span). This will work for most standard devices, choice c("second", "minute", "hour", "day", "week", "month", "year")
.
source to share