I have the first year as 2007
. The last year is 2021
I need to create a character vector just like the vector bellow:
c("2007-2008","2007-2010","2007-2012","2007-2014","2007-2016","2007-2018","2007-2021")
The idea is to have: first-year -second year
, first-year - first-year 3
, first-year - first-year 5
, first-year - first-year 7
, first-year - first-year 9
, first-year - first-year 11
, first-year - first-year 13
But when I have first-year - first-year 13
and the next step is bigger than the last year (2021
) I consider first-year - lastyear
In other words the difference between the last years should be at least 2 (2008....2010...2012...2014..2016...2018...2020) But once I have 2020 it will lead the next interval 2007-2021
have a difference of 1 year, if this happens I consider 2007-2018
and 2007-2021
How can I create something like this in R?
CodePudding user response:
years <- c(2007, 2021)
years <- unique(sort(c(years, seq(1 years[1], years[2], by = 2))))
years
# [1] 2007 2008 2010 2012 2014 2016 2018 2020 2021
years <- years[c(diff(years) >= 2, TRUE)]
years
# [1] 2008 2010 2012 2014 2016 2018 2021
paste(2007, years, sep = "-")
# [1] "2007-2008" "2007-2010" "2007-2012" "2007-2014" "2007-2016" "2007-2018" "2007-2021"
CodePudding user response:
An idea to generate the required sequence directly from seq
st <- 2007
en <- 2021
paste(st, unique(c(seq(st 1, en - 2, 2), en)), sep = "-")
[1] "2007-2008" "2007-2010" "2007-2012" "2007-2014" "2007-2016" "2007-2018"
[7] "2007-2021"