我想在指标值之间的df中切片行。
varx|indicator
23|1
232|0
23|0
434|0
454|0
123|0
2112|1
23|0
232|0
232|0
23|0
22323|1
我想将两个(1)之间的所有值切成一个序列。
答案 0 :(得分:0)
您可以使用Reduce
进行此操作,并使用xor
进行触发器。
df <- read.table(header=TRUE, sep="|", text = "varx|indicator
23|1
232|0
23|0
434|0
454|0
123|0
2112|1
23|0
232|0
232|0
23|0
22323|1")
idx <- Reduce(function(y,x) {xor(y, x==1)}, x=df$indicator, init=FALSE, accumulate=TRUE)
df[idx,]
df[idx[-1] & idx[-length(idx)],]
# varx indicator
#2 232 0
#3 23 0
#4 434 0
#5 454 0
#6 123 0
#Or including the indicators
df[idx[-1] | idx[-length(idx)],]
# varx indicator
#1 23 1
#2 232 0
#3 23 0
#4 434 0
#5 454 0
#6 123 0
#7 2112 1
#12 22323 1