Вариант с использованием data.table
:
#identify indices between MovieStart and MovieEnd
DT[, cs := cumsum(StudioEvent=="MovieStart") - cumsum(StudioEvent=="MovieEnd")]
#perform rolling join to find the start of movies for MovieEnd and indices between MovieStart and MovieEnd
DT[StudioEvent=="MovieEnd" | cs == 1L,
ms := DT[StudioEvent=="MovieStart"][.SD, on=.(Index), roll=Inf, x.Index]
]
#generate sequence
DT[, Sequence := (Index - ms) * 50]
вывод:
Index StudioEvent cs ms Sequence
1: 1 0 NA NA
2: 2 MovieStart 1 2 0
3: 3 1 2 50
4: 4 1 2 100
5: 5 1 2 150
6: 6 1 2 200
7: 7 MovieEnd 0 2 250
8: 8 0 NA NA
9: 9 0 NA NA
10: 10 MovieStart 1 10 0
11: 11 1 10 50
12: 12 1 10 100
13: 13 1 10 150
14: 14 1 10 200
15: 15 MovieEnd 0 10 250
данные:
library(data.table)
DT <- fread("Index,StudioEvent
1,
2,MovieStart
3,
4,
5,
6,
7,MovieEnd
8,
9,
10,MovieStart
11,
12,
13,
14,
15,MovieEnd")