2017-09-26 1 views

Répondre

5

Une option serait rle

inverse.rle(within.list(rle(x), values[values!=0] <- seq_along(values[values!=0]))) 
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6 

Ou avec rleid de data.table

library(data.table) 
x1 <- x*rleid(x) 
match(x1, unique(x1[x1!=0]), nomatch = 0) 
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6 
+1

2ème solution est agréable. Je n'ai pas pensé à utiliser un match comme ça. –