Reputation: 73385
I have got a question relating to Date. I need to determine the date, which is the nearest Tuesday to April 1st, in each year from 1961 to 2006.
As I can check from Calendar, I see the following:
1961 1961-04-04
1962 1962-04-03
1963 1963-04-02
1964 1964-03-31
But, instead of eye spotting them from a Calendar, can I do this easily in R?
The question has a background in air pollution network management. Specifically, the historical Smoke and Sulphur Dioxide Network in the UK operating between 1961 and 2005 was managed on a "pollution year" basis, and such year stars from the date mentioned in this question.
Upvotes: 3
Views: 3316
Reputation: 3239
Here is one solution
nearestTuesday <- function(date) {
delta <- as.POSIXlt(date)$wday - 2
if(abs(delta) < 4)
next_date <- as.Date(date) - delta
else
next_date <- as.Date(date) + (7 - delta)
return(next_date)
}
lapply(ISOdate(1961:2006, 4,1), nearestTuesday)
Upvotes: 5