FrsLry
FrsLry

Reputation: 417

Create all sequences of increasing values

Let's say that I have this vector of years:

allyears <- c("2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020")

I would like to create all contiguous increasing sequences of years, of all lengths:

"2008" "2009"
"2008" "2009" "2010"
"2008" ... "2020"

"2009" "2010"
"2009" "2010" "2011"
"2009" ... "2020"

.
.
.

"2019" "2020"

I tried with expand.grid but it doesn't work because of the different length of the output that I want.

Any idea?

Upvotes: 1

Views: 56

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

You can use nested lapply :

allyears <- sort(as.numeric(allyears))
n <- length(allyears)
lapply(seq_along(allyears)[-n], function(x) 
       lapply(seq(x+1, n), function(y) allyears[x:y]))

#[[1]]
#[[1]][[1]]
#[1] 2008 2009

#[[1]][[2]]
#[1] 2008 2009 2010

#[[1]][[3]]
#[1] 2008 2009 2010 2011

#...
#...

#[[1]][[11]]
# [1] 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019

#[[1]][[12]]
# [1] 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

#...
#...

#[[11]]
#[[11]][[1]]
#[1] 2018 2019

#[[11]][[2]]
#[1] 2018 2019 2020


#[[12]]
#[[12]][[1]]
#[1] 2019 2020

Upvotes: 2

Karthik S
Karthik S

Reputation: 11584

Does this work:

sapply(allyears, function(x) seq(as.integer(x), max(as.integer(allyears))))
$`2008`
 [1] 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

$`2009`
 [1] 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

$`2010`
 [1] 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

$`2011`
 [1] 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

$`2012`
[1] 2012 2013 2014 2015 2016 2017 2018 2019 2020

$`2013`
[1] 2013 2014 2015 2016 2017 2018 2019 2020

$`2014`
[1] 2014 2015 2016 2017 2018 2019 2020

$`2015`
[1] 2015 2016 2017 2018 2019 2020

$`2016`
[1] 2016 2017 2018 2019 2020

$`2017`
[1] 2017 2018 2019 2020

$`2018`
[1] 2018 2019 2020

$`2019`
[1] 2019 2020

$`2020`
[1] 2020

Upvotes: 1

Related Questions