Counting the number of consecutive years in r

我怕爱的太早我们不能终老 提交于 2021-02-08 08:52:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!