dataframe - data frame cumulative run length encoding in R -
i've got data frame containing values relating observations, 1 or 0. want count continual occurrences of 1, resetting @ 0. run length encoding function (rle) seems work can't work out getting data desired format. want try doing without writing custom function. in data below, have observation in data frame, want derive "continual" column , write dataframe. link good start.
observation continual 0 0 0 0 0 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 1 12 0 0 0 0
you can pretty in couple of steps:
x <- rle(mydf$observation) ## run rle on relevant column new <- sequence(x$lengths) ## create sequence of lengths values new[mydf$observation == 0] <- 0 ## replace relevant values 0 new # [1] 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0
Comments
Post a Comment