r - How to extract all rows between start signal and end signal? -
i have following df , extract rows based on following start , end signals.
start signal : when status changes 1 0 end signal : when status changes 0 -1.
df <- data.frame(time = rep(1:14), status = c(0,1,1,0,0,0,-1,0,1,0,0,0,-1,0)) time status 1 1 0 2 2 1 3 3 1 4 4 0 5 5 0 6 6 0 7 7 -1 8 8 0 9 9 1 10 10 0 11 11 0 12 12 0 13 13 -1 14 14 0 desire:
time status 4 4 0 5 5 0 6 6 0 10 10 0 11 11 0 12 12 0
here's possible solution using data.table package. i'm first grouping status == 1 appearances , checking per group if there status == -1, if so, i'm sub-setting group second incident until -1 incident minus 1
library(data.table) setdt(df)[, indx := cumsum(status == 1)] df[, if(any(status == -1)) .sd[2:(which(status == -1) - 1)], = indx] # indx time status # 1: 2 4 0 # 2: 2 5 0 # 3: 2 6 0 # 4: 3 10 0 # 5: 3 11 0 # 6: 3 12 0
Comments
Post a Comment