Reputation: 3634
I'm trying to find all Saturday, Sunday, Monday dates around a series of Sundays. I can get what I want by doing this:
alldays <- Sys.Date() + c(1:100)
allSundays <- alldays[weekdays(alldays)=='Sunday']
length(allSundays) ## 7 elements
nearby <- c(-1,0,1)
result <- c(c(allSundays + nearby[1]),c(allSundays + nearby[2]),c(allSundays + nearby[3]))
length(result) ## 21 elements.
But I'm hoping for a more elegant way of doing it (some form of apply
or some dark data.table
magic?) My apologies if this is a duplicate, but I could not think of good search terms for this (minor) problem.
Upvotes: 1
Views: 112
Reputation: 24074
One way to do what you want is repeating your sunday vector, nearby will be recycle to the right length:
rep(allSundays, e=3) + nearby
all(sort(result)==(rep(allSundays, e=3) + nearby))
#[1] TRUE
Upvotes: 2