user2961410
user2961410

Reputation: 73

Counting the number of consecutive years in r

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.

Upvotes: 2

Views: 752

Answers (1)

Roland
Roland

Reputation: 132949

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

Upvotes: 5

Related Questions