ThomasIsCoding
ThomasIsCoding

Reputation: 102710

partition sequence by barriers of indices

Given a sequence s <- 10:1, is there any elegant function in base R that allows you to set barriers for the indices of s to partition s?

For example, if barriers <- c(3,7), which means the separation occurs at the 3rd and 7th position in s, such that the desired output should be a list of partitions, like

> list(10:8,7:4,3:1)
[[1]]
[1] 10  9  8

[[2]]
[1] 7 6 5 4

[[3]]
[1] 3 2 1

Note that, if barriers <- c(3,10), since nothing left for the partition beyond barrier at 10th position, hence the desired output should be as

> list(10:8,7:1)
[[1]]
[1] 10  9  8

[[2]]
[1] 7 6 5 4 3 2 1

Solution: thanks for the clues provided by @RonakShah and @GKi

split(s, findInterval(seq_along(s), barriers, left.open = TRUE))

Upvotes: 1

Views: 66

Answers (1)

GKi
GKi

Reputation: 39717

You can use split and findInterval like:

s <- 10:1
barriers <- c(3,7)
split(s, findInterval(seq_along(s), barriers, left.open = TRUE))
#$`0`
#[1] 10  9  8
#
#$`1`
#[1] 7 6 5 4
#
#$`2`
#[1] 3 2 1

barriers <- c(3,10)
split(s, findInterval(seq_along(s), barriers, left.open = TRUE))
#$`0`
#[1] 10  9  8
#
#$`1`
#[1] 7 6 5 4 3 2 1

Upvotes: 1

Related Questions