r - Resetting TIME column when AMT > 0 -


i have data frame looks this:

id  time  amt 1    0    50 1    1    0 1    2    0 1    3    0 1    4    0 1    4    50 1    5    0 1    7    0 1    9    0 1    10   0 1    10   50 

the time column in above data frame continuous. want add time column resets time 0 when amt>0. so, output data frame should this:

    id  time  amt  time2     1    0    50    0     1    1    0     1      1    2    0     2      1    3    0     3      1    4    0     4     1    4    50    0     1    5    0     1     1    7    0     3     1    9    0     5     1    10   0     6     1    10   50    0 

this achieved subtracting time "fixed" reference time when amt>0 (for example; reference time second amt>0 4. so, time2 calculated subtracting 5-4=1 ;7-4=3; 9-4=5 etc. how can automatically in r.

a data.table solution :

library(data.table) setdt(dt)[,time2 := time-time[1],cumsum(amt>0)]  #      id time amt time2 # 1:   1    0  50     0 # 2:   1    1   0     1 # 3:   1    2   0     2 # 4:   1    3   0     3 # 5:   1    4   0     4 # 6:   1    4  50     0 # 7:   1    5   0     1 # 8:   1    7   0     3 # 9:   1    9   0     5 # 10:  1   10   0     6 # 11:  1   10  50     0 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -