This seems to work
df <- data.frame(Delta=c(0, 32, 32, 32, 32, 31, 31, 29),
TimeMS=c(0, 32, 64, 96, 128, 159, 190, 219),
Marker=c("Start", "NA", "NA", "Stop", "NA", "NA", "Start", "NA"))
df$group <- cumsum(df$Marker=="Start" & !is.na(df$Marker))
df$Latency <- unlist(aggregate(TimeMS~group,df,function(x)cumsum(c(0,diff(x))))$TimeMS)
df[,"group"] <- NULL
df
# Delta TimeMS Marker Latency
# 1 0 0 Start 0
# 2 32 32 NA 32
# 3 32 64 NA 64
# 4 32 96 Stop 96
# 5 32 128 NA 128
# 6 31 159 NA 159
# 7 31 190 Start 0
# 8 29 219 NA 29
First we add a column, df$group
which increments by 1 every time df$Marker=="Start"
(so, df$group=1
for rows 1:6 and =2 for rows 7:8). Then we aggregate TimeMS
by group using the diff(...)
function. Applied to a vector of length n, diff(...)
returns a vector of length n-1 containing the difference between a given row and the previous row. So we need to insert a 0 a the beginning of this vector. aggregate(...)
returns two sets of vectors (one for group==1
, and one for group==2
), so we need to unlist(...)
into a single vector before binding to df
. The last line just removes df$group