Reputation: 3920
I have a certain start time and a specified day of the week.
start = as.POSIXct(1234567, origin = "1970-1-1")
format(start, format = "%A %c")
target1 = "TUE"
target2 = "Wednesday"
What I want is to find the first day, following start, that matches the corresponding day of the week. (And hopefully is somewhat flexible as to how the user might input the day of the week target) Any idea? I imagine a string lookup table might work, but there's gotta be a neater way.
Bonus points if the solution can be made to vectorise....
Upvotes: 2
Views: 179
Reputation: 173527
I haven't tried vectorizing this yet (not sure if I can), but here's an attempt:
find_day <- function(start,target){
target <- tolower(target)
next_week <- as.Date(start) + 1:7
next_week[match(target,substr(tolower(weekdays(next_week)),1,nchar(target)))]
}
It should accept any length or capitalized abbreviation of a day. How to use it:
> find_day(start,"TUE")
[1] "1970-01-20"
> find_day(start,"friday")
[1] "1970-01-16"
Upvotes: 2