Serban Tanasa Serban Tanasa - 1 month ago 4x
R Question

How do add multiple values to each element of a vector

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
or some dark
magic?) My apologies if this is a duplicate, but I could not think of good search terms for this (minor) problem.


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