Generate a list from a vector in r

Viewed 32

I have a vector like a. I would like to generate a list b from a. I only typed the first 4 components of the list. Any suggestions of quick ways to achieve this be appreciated:

a <- seq(from =0, to = 359, by = 8) 
b <- list(c(0:7), c(8:(8+7)), c(16:(16+7)), c(24:(24+7)))

> b
[[1]]
[1] 0 1 2 3 4 5 6 7

[[2]]
[1]  8  9 10 11 12 13 14 15

[[3]]
[1] 16 17 18 19 20 21 22 23

[[4]]
[1] 24 25 26 27 28 29 30 31
2 Answers

You can create a sequence from min value of a to max and then use findInterval or cut to split the sequence based on intervals.

tmp <- seq(min(a), max(a))
split(tmp, findInterval(tmp, a))

#$`1`
#[1] 0 1 2 3 4 5 6 7

#$`2`
#[1]  8  9 10 11 12 13 14 15

#$`3`
#[1] 16 17 18 19 20 21 22 23

#$`4`
#[1] 24 25 26 27 28 29 30 31

#$`5`
#[1] 32 33 34 35 36 37 38 39

#...

Another way using Map :

Map(seq, a[-length(a)], a[-1] - 1)

This will achieve the desired result

list1 <- list()

for (i in 1:45) {
  base=i*8-8
  list1[[i]] <- base + 1:8
}
Related