Create counter of consecutive runs of a certain value

后端 未结 3 1176
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 20:13

I have data where consecutive runs of zero are separated by runs of non-zero values. I want to create a counter for the runs of zero in the column \'SOG\'.

For the fi

3条回答
  •  旧巷少年郎
    2020-12-10 21:01

    SOG <- c(4,4,0,0,0,3,4,5,0,0,1,2,0,0,0)
    #run length encoding:
    tmp <- rle(SOG)
    #turn values into logicals
    tmp$values <- tmp$values == 0
    #cumulative sum of TRUE values
    tmp$values[tmp$values] <- cumsum(tmp$values[tmp$values])
    #inverse the run length encoding
    inverse.rle(tmp)
    #[1] 0 0 1 1 1 0 0 0 2 2 0 0 3 3 3
    

提交回复
热议问题