You can use rle
in base R :
df$runtime <- with(rle(df$activity != 'idle'),
rep(cumsum(values) * values, lengths))
df
# time activity runtime
#1 19:01 idle 0
#2 19:02 task1 1
#3 19:03 task2 1
#4 19:04 idle 0
#5 19:05 idle 0
#6 19:06 idle 0
#7 19:07 task2 2
#8 19:08 task2 2
#9 19:09 task2 2
#10 19:10 task1 2
#11 19:11 idle 0
#12 19:12 task1 3
For every group of values that is not 'idle'
we increment the count by 1 to create runtime
.
To combine smaller times in the same runtime
you can do :
df$runtime <- with(rle(df$activity != 'idle'),
rep(cumsum(values & lengths > 1) * values, lengths))
df
# time activity runtime
#1 19:01 idle 0
#2 19:02 task1 1
#3 19:03 task2 1
#4 19:04 idle 0
#5 19:05 idle 0
#6 19:06 idle 0
#7 19:07 task2 2
#8 19:08 task2 2
#9 19:09 task2 2
#10 19:10 task1 2
#11 19:11 idle 0
#12 19:12 task1 2
data
df <- structure(list(time = c("19:01", "19:02", "19:03", "19:04", "19:05",
"19:06", "19:07", "19:08", "19:09", "19:10", "19:11", "19:12"
), activity = c("idle", "task1", "task2", "idle", "idle", "idle",
"task2", "task2", "task2", "task1", "idle", "task1")), row.names = c(NA,
-12L), class = "data.frame")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…