1) Calculate the values and then the lengths based on the values
s <- split(x, cumsum(c(0, diff(x) != 1))) run.info <- list(lengths = unname(sapply(s, length)), values = unname(s))
Running with x from the question gives the following:
> str(run.info) List of 2 $ lengths: int [1:5] 3 6 1 2 6 $ values :List of 5 ..$ : num [1:3] 3 4 5 ..$ : num [1:6] 10 11 12 13 14 15 ..$ : num 17 ..$ : num [1:2] 22 23 ..$ : num [1:6] 35 36 37 38 39 40
2) Calculate lengths and then values based on lengths
Here is a second solution based on calculating the length of Gregor :
lens <- rle(x - seq_along(x))$lengths list(lengths = lens, values = unname(split(x, rep(seq_along(lens), lens))))
3) Calculate lengths and values without using others
This seems inefficient, as it computes each of the lengths and values from scratch, and it also seems somewhat overly complicated, but it manages to reduce it all to one statement, so I thought I would add it, Its basically just a mixture of the two previous solutions marked 1) and 2) above. Nothing really new about the two.
list(lengths = rle(x - seq_along(x))$lengths, values = unname(split(x, cumsum(c(0, diff(x) != 1)))))
EDIT: Added second solution.
EDIT: Added third solution.
G. grothendieck
source share