您可以完全使用rle()
并避免编写 for/while 循环:
x <- c(-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,11,10,9,8,7,6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12)
result <- rep(99, length(x))
result[x >= 5] <- 1
result[x <= 0] <- 0
result
# [1] 0 0 0 0 0 99 99 99 99 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 99
# [26] 99 99 99 0 0 0 0 0 99 99 99 99 1 1 1 1 1 1 1 1
# Run-length-encode it
result_rle <- rle(result)
# Find the 99's and replace them with the previous value
missing_idx <- which(result_rle$values == 99)
result_rle$values[missing_idx] <- result_rle$values[missing_idx - 1]
# Inverse of the RLE
result <- inverse.rle(result_rle)
# Check value
expected <- c(0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1)
identical(result, expected)
# TRUE
请注意,如果第一个值介于 0 和 5 之间,这将给出错误,但添加一个检查很简单。你还需要决定在这种情况下你想要什么行为。