add reversed indices based on indicator

Viewed 42

I have a vector like this

v <- c(0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0)

I now want to generate a second vector that counts backwards until it hits a 1, then starts over.

The result here would be

r <- c(6,5,4,3,2,1,8,7,6,5,4,3,2,1,4,3,2,1,0)

the last zero should be kept

I tried something like this but cannot get it to work:

lv <- c(1, which(v == 1))

res <- c()
for(i in 1:(length(lv)-1)) {
  res <- c(res, rev(lv[i]:lv[i+1]))
}
1 Answers

We can use ave creating groups with cumsum and count the sequence in reverse in each group. We then re assign 1 to their original position in new_seq.

new_seq <- ave(v, cumsum(v==1), FUN = function(x) rev(seq_along(x))) + 1
new_seq[v == 1] <- 1

new_seq
#[1] 6 5 4 3 2 1 8 7 6 5 4 3 2 1 4 3 2 1 2

Update

To keep everything after last 1 as it is we can do

#Make groups
indx <- cumsum(v==1)

#Create reverse sequential counting in each group
new_seq <- ave(v, indx, FUN = function(x) rev(seq_along(x))) + 1

#Keep everything after last 1 as it is
new_seq[which.max(indx) : length(v)] <- v[which.max(indx) : length(v)]

#Change 1's same as their original position
new_seq[v == 1] <- 1

new_seq
#[1] 6 5 4 3 2 1 8 7 6 5 4 3 2 1 4 3 2 1 0
Related