r - Incrementation with multiple conditions -


this question add-on this one. thought additional condition substantial enough create new question.

i have dataframe of dates , events below.

data <- data.frame( date= as.date(c(rep("24.07.2012",12), rep("25.07.2012",8)), format="%d.%m.%y"),                      event=rep(0,20)   ) data$event[10] <- 1 data$event[15] <- 1 

i want add start counter column increments in 10's , reset:

  • 1) right after event=1 observed.
  • 2) when date has changed previous row.

so desired output additional start column be:

         date   event start 1  2012-07-24     0     0 2  2012-07-24     0    10 3  2012-07-24     0    20 4  2012-07-24     0    30 5  2012-07-24     0    40 6  2012-07-24     0    50 7  2012-07-24     0    60 8  2012-07-24     0    70 9  2012-07-24     0    80 10 2012-07-24     1    90 11 2012-07-24     0     0 12 2012-07-24     0    10 13 2012-07-25     0     0 14 2012-07-25     0    10 15 2012-07-25     1    20 16 2012-07-25     0     0 17 2012-07-25     0    10 18 2012-07-25     0    20 19 2012-07-25     0    30 20 2012-07-25     0    40 

the linked question has solutions cater condition 1.

with addition of condition 2, need keep track of date value (n-1)th row. guessing complicates solution.

any ideas tackle without for loop?

library(data.table) setdt(data) data[, start := 10 * (seq_along(event) - 1),       by=list(date, cumsum(c(1l, diff(event) == -1l)))] #turn data.table data.frame: class(data) <- "data.frame" 

as @david arenburg reminds me, there setdf same , additional clean-up.

data #         date event start #1  2012-07-24     0     0 #2  2012-07-24     0    10 #3  2012-07-24     0    20 #4  2012-07-24     0    30 #5  2012-07-24     0    40 #6  2012-07-24     0    50 #7  2012-07-24     0    60 #8  2012-07-24     0    70 #9  2012-07-24     0    80 #10 2012-07-24     1    90 #11 2012-07-24     0     0 #12 2012-07-24     0    10 #13 2012-07-25     0     0 #14 2012-07-25     0    10 #15 2012-07-25     1    20 #16 2012-07-25     0     0 #17 2012-07-25     0    10 #18 2012-07-25     0    20 #19 2012-07-25     0    30 #20 2012-07-25     0    40 

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -