4

I have a vector of numbers.

initialindex= c(17,  23,  28,  34,  39,  45)

What I would like to get out of this looks like this:

finalindex=c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5)

The number repeats based on the difference of initialindex. 23-17= 6 1's and 28-23= 5'2s.

I can take the diff of initial index:

diff(initialindex)

which will give me the length of each value in the final index (6 1's, 5 2's, 6 3's). But, then I need to replicate them with the new index value 1: len(initialindex)

Can anyone help me with this?

Tracy

Tracy
  • 699
  • 2
  • 9
  • 21

3 Answers3

3

One option could be:

cumsum(sequence(diff(initialindex)) == 1)

 [1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
2

A solution using rep – first proposed by @gung - Reinstate Monica but was deleted

rep(x = 1:(length(initialindex) - 1L),
    times = diff(initialindex))
# [1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
markus
  • 25,843
  • 5
  • 39
  • 58
1

Using inverse.rle

x <- rle(0)
x$lengths <- diff(initialindex)
x$values <- seq_along(x$lengths)
inverse.rle(x)

[1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
manotheshark
  • 4,297
  • 17
  • 30