這裏是基於rle
和cumsum
的解決方案。我正在添加評論來解釋主要步驟,即使很難用文字來解釋它。該解決方案是矢量化的,沒有任何循環。
## init the vectors results with zeros
dx$index <- rep(0,nrow(dx))
dx$total_time <- rep(0,nrow(dx))
## use rle to get the position/length
rr <- rle(dx$output)
## only the val 2 is important for us , so we store into index
ii <- rr$values==2
## we replace the occuronce of 2 in the original vector by the cumulative
## repeating it : hard to explain !!
vals <- cumsum(ii)[ii]
occurs <- rr$len[ii]
dx$index[dx$output==2] <- rep(vals,occurs)
## same thing for the total just we change the value here
dx$total_time[dx$output==2] <- rep(occurs*2,occurs)
# Time output index total_time
# 1 2 1 0 0
# 2 2 1 0 0
# 3 2 2 1 4
# 4 2 2 1 4
# 5 2 1 0 0
# 6 2 2 2 2
# 7 2 1 0 0
,其中作爲DX閱讀:
dx <- read.table(text=" Time output
2 1
2 1
2 2
2 2
2 1
2 2
2 1",header=T)
謝謝你這個作品! – amy