Reputation: 709
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
Upvotes: 4
Views: 164
Reputation: 26343
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
Upvotes: 2
Reputation: 4357
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
Upvotes: 1
Reputation: 39868
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
Upvotes: 3