R How to get the difference between current and next row that matches certain condition? -


i understand question seems bit confusing. 1 example be,

                          time        x     2017-07-24 12:33:13.000000      0.0     2017-07-24 12:33:14.000000      0.0     2017-07-24 12:33:15.000000      0.0     2017-07-24 12:33:16.000000      0.0     2017-07-24 12:33:16.500000      1.0     2017-07-24 12:33:17.000000      0.0     2017-07-24 12:33:17.500000      0.0     2017-07-24 12:33:18.500000      1.0 

in r, want have column that, each row, compute difference between time current row , time next row x not 0. results this:

                          time        x     diff     2017-07-24 12:33:13.000000      0.0      3.5     2017-07-24 12:33:14.000000      0.0      2.5     2017-07-24 12:33:15.000000      0.0      1.5     2017-07-24 12:33:16.000000      0.0      0.5     2017-07-24 12:33:16.500000      1.0      0.0     2017-07-24 12:33:17.000000      0.0      1.5     2017-07-24 12:33:17.500000      0.0      1.0     2017-07-24 12:33:18.500000      1.0      0.0 

thank answering in advance.

finding rows "x == 1":

wh = which(dat$x == 1) 

we can build vector of indices of nearest (forward) "1":

i = rep(wh, c(wh[1], diff(wh))) 

and subtract respective "time"s:

dat$time[i] - dat$time #time differences in secs #[1] 3.5 2.5 1.5 0.5 0.0 1.5 1.0 0.0 

"dat" is:

dat = structure(list(time = structure(c(1500888793, 1500888794, 1500888795,  1500888796, 1500888796.5, 1500888797, 1500888797.5, 1500888798.5 ), class = c("posixct", "posixt"), tzone = ""), x = c(0, 0, 0,  0, 1, 0, 0, 1)), .names = c("time", "x"), row.names = c(na, 8l ), class = "data.frame") 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -