在R中,这样的矢量:
x <- c(0,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,0,1)
我希望x是这样的:
y = c(0,0,1,1,0,0,2,2,0,0,3,3,3,3,0,4,0,5,0,6)
有人可以帮我解决这个问题吗?
答案 0 :(得分:5)
选项为rle
inverse.rle(within.list(rle(x), values[values!=0] <- seq_along(values[values!=0])))
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6
或rleid
data.table
library(data.table)
x1 <- x*rleid(x)
match(x1, unique(x1[x1!=0]), nomatch = 0)
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6