I have a problem. For example, I have this:
id truth count 1 1 1 2 1 2 3 0 0 4 1 1 5 1 2 6 1 3 8 0 0
I tried this:
fun <- rle(df$truth) df$count <- unlist(sapply(fun$lengths, function(x) {return(1:x)}))
But it does not work.
Here is the approach. Based on ave :
ave
transform(dat, count = truth * ave(truth, c(0L, cumsum(diff(truth) != 0)), FUN = seq_along))
where dat is the name of your data frame.
dat