[R] Elegant way to get specific dates within prespecified period
Frank S.
f_j_rod at hotmail.com
Fri Sep 30 18:38:02 CEST 2016
Dear R users,
I have two dates, ["open", "close"], which can be any dates such "close" is strictly later than "open".
I wanted to write an R code that displays the following: To construct a vector "v" with all 1st January
days located between "open" and "close" dates: v = (dp_1, dp_2, ..., dp_n). Moreover:
a) Regard to the first date "dp_1":
a1) If "open" is on a 1st January day, "dp_1" is on 1st January of the year after "open".
a2) In case difftime between "open" and the following 1st January is lower than 30 days,
"dp_1" will be on 1st January of the year after the year of that 1st January.
b) Regard to the last date "dp_n":
b1) If "close" is on a 1st January day, dp_n is on 1st January of the year before "close"
b2) In case difftime between "close" and the previous 1st January is lower than 30 days,
"dp_n" will be on 1st January of the year before the year of that 1st January.
Example 1: [open = 2007-01-01, close = 2011-04-05]
v = (2008-01-01, 2009-01-01, 2010-01-01, 2011-01-01) # Since open is already on a 1st January
# Since difftime(2011-04-05, 2011-01-01) >= 30 days
Example 2: [open = 2006-12-15, close = 2011-01-19]
v = (2008-01-01, 2009-01-01, 2010-01-01) # Since difftime(2007-01-01, 2006-12-15) < 30 days
# Since difftime(2011-01-19, 2011-01-01) < 30 days
My code is (for example 2):
open <- as.Date('2006-12-15')
close <- as.Date('2011-01-19')
dp_1 <- as.Date(ifelse(
as.Date(paste(as.character(as.numeric(format(open, "%Y")) + 1), 1, 1, sep = "-")) - open >= 30,
as.Date(paste(as.character(as.numeric(format(open, "%Y")) + 1), 1, 1, sep = "-")),
as.Date(paste(as.character(as.numeric(format(open, "%Y")) + 2), 1, 1, sep = "-"))),
origin = "1970-01-01")
dp_n <- as.Date(ifelse(
close - as.Date(paste(as.character(as.numeric(format(close, "%Y"))), 1, 1, sep = "-")) >= 30,
as.Date(paste(as.character(as.numeric(format(close, "%Y"))), 1, 1, sep = "-")),
as.Date(paste(as.character(as.numeric(format(close, "%Y")) - 1), 1, 1, sep = "-"))),
origin = "1970-01-01")
v <- seq(dp_1, dp_n, by = "year")
However, above code is not too large, so I'm almost sure that there might be a better way of doing it.
Is there a better way to get the vector "v"?
Thanks for any help!
Frank S.
[[alternative HTML version deleted]]
More information about the R-help
mailing list