问题
I have a vector A containing years: eg.
A <- c(1978, 1979, 1980, 1981, 1984, 1987,1988,1989,1990,1991, 1992)
I would like to be able to count the sequence of years before a year is missed out. So I would be looking for my answer to be : 4, 1, 6
I know about using rle
for sequences of repeated numbers but not sure what to do here.
回答1:
Assuming A
is sorted:
A <- c(1978, 1979, 1980, 1981, 1984, 1987,1988,1989,1990,1991, 1992)
B <- cumsum(c(1, diff(A)>1))
rle(B)$lengths
#[1] 4 1 6
来源:https://stackoverflow.com/questions/23785911/counting-the-number-of-consecutive-years-in-r